Java 中 Throwable 类及其方法的重要性是什么?


Throwable 类是 Java 中所有错误和异常的超类。此类的对象实例由 **Java 虚拟机** 抛出,或者可以由 **throw** 语句抛出。类似地,此类或其子类之一可以是 catch 子句中的参数类型。

两个子类 **Error** 和 **Exception** 的实例用于指示发生了异常情况,这些实例是在异常情况的上下文中创建的,以包含相关信息。

Throwable 类常用的异常方法

  • public String getMessage(): 返回关于异常的消息字符串。
  • public Throwable getCause(): 返回异常的原因。如果原因未知或不存在,则返回 null。
  • public String toString(): 返回异常的简短描述。
  • public void printStackTrace(PrintStream s): 在错误输出流 (System.err) 上打印异常的简短描述 (使用 toString()) + 此异常的堆栈跟踪。

示例

在线演示

class ArithmaticTest {
   public void division(int num1, int num2) {
      try {
         //java.lang.ArithmeticException here.
         System.out.println(num1/num2);
         //catch ArithmeticException here.
      } catch(ArithmeticException e) {
         //print the message string about the exception.
         System.out.println("getMessage(): " + e.getMessage());
         //print the cause of the exception.
         System.out.println("getCause(): " + e.getCause());
         //print class name + “: “ + message.
         System.out.println("toString(): " + e.toString());
         System.out.println("printStackTrace(): ");
         //prints the short description of the exception + a stack trace for this exception.
         e.printStackTrace();
      }
   }
}
public class Test {
   public static void main(String args[]) {
      //creating ArithmaticTest object
      ArithmaticTest test = new ArithmaticTest();
      //method call
      test.division(20, 0);
   }
}

输出

getMessage(): / by zero
getCause(): null
toString(): java.lang.ArithmeticException: / by zero
printStackTrace():
java.lang.ArithmeticException: / by zero
at ArithmaticTest.division(Test.java:5)
at Test.main(Test.java:27)

更新于:2020年2月6日

397 次浏览

启动您的 职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.