如何在 Java 中创建自定义未检查异常?

javaobject oriented programmingprogramming更新于 2024/5/11 21:03:00

我们可以通过扩展 Java 中的 RuntimeException 来创建自定义未检查异常

未检查异常继承自 Error 类或 RuntimeException 类。许多程序员认为我们无法在程序中处理这些异常,因为它们代表了程序在运行时无法恢复的错误类型。抛出未检查异常通常是由于代码误用 传递 null 或其他不正确的参数所致。

语法

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

实现未检查异常

自定义未检查异常的实现与 Java 中的已检查异常几乎相似。唯一的区别是,未检查异常必须扩展 RuntimeException ,而不是 Exception。

示例

public class CustomUncheckedException extends RuntimeException {
   /*
   * 当我们想在抛出异常时添加自定义消息时需要
   * as throw new CustomUncheckedException(" Custom Unchecked Exception ");
   */
   public CustomUncheckedException(String message) {
      // 调用 super 会调用所有超类的构造函数
      // 这有助于创建完整的堆栈跟踪。
      super(message);
   }
   /*
   * 当我们想要包装 catch 块内生成的异常并重新抛出它时,这是必需的
   * as catch(ArrayIndexOutOfBoundsException e) {
      * throw new CustomUncheckedException(e);
   * }
   */
   public CustomUncheckedException(Throwable cause) {
      // 调用适当的父构造函数
      super(cause);
   }
   /*
   * 当我们需要上述两者时,它是必需的
   * as catch(ArrayIndexOutOfBoundsException e) {
      * throw new CustomUncheckedException(e, "File not found");
   * }
   */
    public CustomUncheckedException(String message, Throwable throwable) {
      // 调用适当的父构造函数
      super(message, throwable);
   }
}

相关文章