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


prtyaa
prtyaa 2024-01-08 22:49:44 51927 赞同 0 反对 0
分类: 资源 标签: 运维
我们可以通过扩展 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);
}
}

如果您发现该资源为电子书等存在侵权的资源或对该资源描述不正确等,可点击“私信”按钮向作者进行反馈;如作者无回复可进行平台仲裁,我们会在第一时间进行处理!

评价 0 条
prtyaaL2
粉丝 1 资源 1949 + 关注 私信
最近热门资源
银河麒麟桌面操作系统备份用户数据  123
统信桌面专业版【全盘安装UOS系统】介绍  118
银河麒麟桌面操作系统安装佳能打印机驱动方法  109
银河麒麟桌面操作系统 V10-SP1用户密码修改  103
最近下载排行榜
银河麒麟桌面操作系统备份用户数据 0
统信桌面专业版【全盘安装UOS系统】介绍 0
银河麒麟桌面操作系统安装佳能打印机驱动方法 0
银河麒麟桌面操作系统 V10-SP1用户密码修改 0
作者收入月榜
1

prtyaa 收益393.62元

2

zlj141319 收益218元

3

1843880570 收益214.2元

4

IT-feng 收益209.03元

5

风晓 收益208.24元

6

777 收益172.71元

7

Fhawking 收益106.6元

8

信创来了 收益105.84元

9

克里斯蒂亚诺诺 收益91.08元

10

技术-小陈 收益79.5元

请使用微信扫码

加入交流群

请使用微信扫一扫!