语法
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);
}
}
如果您发现该资源为电子书等存在侵权的资源或对该资源描述不正确等,可点击“私信”按钮向作者进行反馈;如作者无回复可进行平台仲裁,我们会在第一时间进行处理!
加入交流群
请使用微信扫一扫!