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

WBOY
WBOY 转载
2023-09-11 16:37:02 921浏览

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

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

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

语法
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);
   }
}

以上就是如何在Java中创建自定义的未检查异常?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除