I am trying to add an exception to my code so that an exception is thrown whenever securityManager returns 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;
However when I add this I have a syntax error:
Unhandled exception type InstantiationException
And the IDE wants to add the line:
public Appointment(String date,String time) throws InstantiationException
However when I do this, the exception always triggers.
How do I reformat the code so the exception only occurs whenever securityManager returns false?
InstantiationException
is a checked exception. You must handle it, otherwise, the compiler will complain about this exception.
Examples of checked exceptions are ClassNotFoundException
, IOException
, SQLException
, etc.
If you wanna raise the exception in the running time, you can use the unchecked Exception which are subtypes of Error
and RuntimeException
. IDE will never ask for handling these exceptions.