overridden method does not throw exception
The compiler is issuing an error because Java does not allow you to override a method and add a checked Exception (any user-defined custom exception that extends the Exception
class). Because it is clear that you want to handle the scenario where some condition is not met as an unexpected occurrence (a bug), your best option is to throw a RuntimeException
. A RuntimeException
, such as: IllegalArgumentException
or NullPointerException
, does not have to be included in a method signature, so you will alleviate your compiler error.
I suggest the following changes to your code:
//First: Change the base class exception to RuntimeException:
public class NoSuchElementException extends RuntimeException {
public NoSuchElementException(String message){
super(message);
}
}
//Second: Remove the exception clause of the getId signature
//(and remove the unnecessary else structure):
public int getId(....) {
if ( condition is met) { return variable; }
//Exception will only be thrown if condition is not met:
throw new NoSuchElementException (message);
}