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 次瀏覽

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告