I have a problem when compiling my code, I'm trying to make a method of a class throw an personalized exception, given some conditions. But at the time of compiling I get the message:
Overridden method does not throw exception
Here's the class and exception declaration:
public class UNGraph implements Graph
Graph
is an interface with all the methods of UNGraph
in it (the method getId()
doesn't have the throws
declaration on that script)
After the constructor I create the exception (inside the class UNGraph):
public class NoSuchElementException extends Exception {
public NoSuchElementException(String message){
super(message);
}
}
Here is the method with the exception
public int getId(....) throws NoSuchElementException {
if (condition is met) {
//Do method
return variable;
}
else{
throw new NoSuchElementException (message);
}
}
Obviously I don't want the method to throw an exception every time, just when the condition is not met; and when it's met, I want to return a variable.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…