java - 未处理的异常类型 Java InstantiationException
问题描述
我正在尝试向我的代码添加一个异常,以便每当 securityManager 返回 false 时都会引发异常:
public Appointment(String date,String time) {
//Secure Object Construction
if (securityManager(date, time)) {
this.date=date;
this.time=time;
System.out.println("Valid");
}
//Invalid Object, Throw Error
else {
throw new InstantiationException("Date provided is Invalid");
}
return;
但是,当我添加这个时,我有一个语法错误:
Unhandled exception type InstantiationException
IDE 想要添加以下行:
public Appointment(String date,String time) throws InstantiationException
但是,当我这样做时,总是会触发异常。
如何重新格式化代码,以便仅在 securityManager 返回 false 时发生异常?
解决方案
InstantiationException
是一个检查异常。你必须处理它,否则编译器会报这个异常。
已检查异常的示例有ClassNotFoundException
、IOException
、SQLException
等。
如果你想在运行时引发异常,你可以使用未检查的异常,它是Error
和的子类型RuntimeException
。IDE 永远不会要求处理这些异常。
推荐阅读
- django - 一种形式的Django多个相同的依赖下拉框
- flutter - 如何根据颤动的条件渲染小部件?
- java - 使用 Feign 创建 SDK 库
- c++ - (国际象棋)negamax 搜索缺少将死的问题
- javascript - NextJS 动态 SSR:错误卡在移动设备中加载
- api - 一般问题 - API / 支付 / 仪表板
- ios - 如何在 Swift 中进行嵌套在另一个 API 失败回调中的同步 API 调用
- api - mongo find() 查询响应中缺少数据
- java - Tomcat 上的 SSL 证书 - 别名 (tomcat) 无法识别密钥
- amazon-web-services - 将数据从 AWS DynamoDB 传输到 AWS S3 存储桶中的单个文件的最佳方式?