我正在尝试向我的代码添加异常,以便每当 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
等。
如果你想在运行时引发异常,你可以使用unchecked Exception,它是Error
和RuntimeException
的子类型。 IDE 永远不会要求处理这些异常。
关于java - 未处理的异常类型 Java InstantiationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60760319/