Java 中的鏈式異常\n


鏈式異常有助於關聯一個異常與其他異常。通常我們需要丟擲一個自定義異常,並希望保留原始異常的詳細資訊,在這種情況下,我們可以使用鏈式異常機制。考慮以下示例,在保持原始異常訊息的前提下,我們丟擲自定義異常。

示例

線上演示

public class Tester {
   public static void main(String[] args) {
      try {
         test();
      }catch(ApplicationException e) {          
         System.out.println(e.getMessage());
      }
   }  

   public static void test() throws ApplicationException {
      try {
         int a = 0;
         int b = 1;
         System.out.println(b/a);
      }catch(Exception e) {
         throw new ApplicationException(e);
      }
   }
}

class ApplicationException extends Exception {
   public ApplicationException(Exception e) {          
      super(e);
   }
}

輸出

java.lang.ArithmeticException: / by zero

throwable 類使用以下方法支援鏈式異常

建構函式

  • Throwable(Throwable cause) - 原因是當前的異常。

  • Throwable(String msg, Throwable cause) - msg 是異常訊息,cause 是當前的異常。

方法

  • getCause - 返回實際的原因。

  • initCause(Throwable cause) - 設定呼叫異常的原因。

更新日期: 18-Jun-2020

2K+ 瀏覽量

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.