如何在 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);
}
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP