在java中打印异常信息的不同方法有哪些?
异常是在程序执行期间发生的 issue(运行时错误)。当出现异常时,该程序会突然终止执行,而生成异常的那行代码后面的代码将永远不会被执行。
打印异常消息
你可以使用从 Throwable 类继承的以下方法之一来打印 Java 中的异常消息。
printStackTrace() - 该方法会将回溯信息打印到标准错误流。
getMessage() - 该方法返回当前 throwable 对象的详细消息字符串。
toString() - 该消息会打印出当前 throwable 对象的简短描述。
示例
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)
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP