在Java中打印异常消息有哪些不同的方法?
例外是程序执行期间发生的问题(运行时错误)。发生异常时,程序会突然终止,并且生成异常的行之后的代码将永远不会执行。
打印异常消息
您可以使用从Throwable类继承的以下方法之一在Java中打印异常消息。
printStackTrace()-此方法将回溯打印到标准错误流。
getMessage()-此方法返回当前可抛出对象的详细消息字符串。
toString()-此消息显示当前可抛出对象的简短描述。
示例
import java.util.Scanner;
public class PrintingExceptionMessage {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number: ");
int a = sc.nextInt();
System.out.println("Enter second number: ");
int b = sc.nextInt();
try {
int c = a/b;
System.out.println("The result is: "+c);
}
catch(ArithmeticException e) {
System.out.println("Output of printStackTrace() method: ");
e.printStackTrace();
System.out.println(" ");
System.out.println("Output of getMessage() method: ");
System.out.println(e.getMessage());
System.out.println(" ");
System.out.println("Output of toString() method: ");
System.out.println(e.toString());
}
}
}输出结果
Enter first number: 10 Enter second number: 0 Output of printStackTrace() method: java.lang.ArithmeticException: / by zero Output of getMessage() method: / by zero Output of toString() method: java.lang.ArithmeticException: / by zero at PrintingExceptionMessage.main(PrintingExceptionMessage.java:11)
热门推荐
1 狗狗下楼训练
3 狗狗训练头盔
6 狗狗训练机构
7 训练狗狗步骤
9 狗狗能训练
10 狗狗基本动作训练方法
11 怎么训练狗狗叼饭盆
12 狗狗一岁了还能训练吗
13 训练狗狗的
14 宁波狗狗训练
15 训练狗狗拉屎
16 教狗狗训练
17 狗狗要怎么训练上厕所
18 狗狗靠的训练