在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)