如何在 Java 中建立自定義未檢查異常?


我們透過在 Java 中擴充套件 RuntimeException 來建立自定義未檢查 異常 

未檢查 異常 繼承自 Error 類或 RuntimeException 類。許多程式設計師認為我們不能在程式中處理這些異常,因為它們代表了程式在執行時無法從其恢復的型別錯誤。當丟擲未檢查異常時,通常會導致錯誤使用程式碼 傳遞空值 或其他不正確的引數

語法

public class MyCustomException extends RuntimeException {
   public MyCustomException(String message) {
      super(message);
   }
}

實現未檢查異常

在 Java 中自定義未檢查異常的實現幾乎與檢查異常類似。唯一的區別在於未檢查異常必須擴充套件 RuntimeException 而不是 Exception。

示例

public class CustomUncheckedException extends RuntimeException {
   /*
   * Required when we want to add a custom message when throwing the exception
   * as throw new CustomUncheckedException(" Custom Unchecked Exception ");
   */
   public CustomUncheckedException(String message) {
      // calling super invokes the constructors of all super classes
      // which helps to create the complete stacktrace.
      super(message);
   }
   /*
   * Required when we want to wrap the exception generated inside the catch block and rethrow it
   * as catch(ArrayIndexOutOfBoundsException e) {
      * throw new CustomUncheckedException(e);
   * }
   */
   public CustomUncheckedException(Throwable cause) {
      // call appropriate parent constructor
      super(cause);
   }
   /*
   * Required when we want both the above
   * as catch(ArrayIndexOutOfBoundsException e) {
      * throw new CustomUncheckedException(e, "File not found");
   * }
   */
   public CustomUncheckedException(String message, Throwable throwable) {
      // call appropriate parent constructor
      super(message, throwable);
   }
}

更新日期: 2020-02-07

9K+ 瀏覽

開啟你的 職業

完成課程以獲得認證

開始學習
廣告