编译我的代码时遇到问题,我试图让一个类的方法抛出一个个性化的异常,给定一些条件.但在编译时我得到的信息是:
Overridden method does not throw exception
这是类和异常声明:
public class UNGraph implements Graph
Graph是一个包含UNGraph所有方法的接口(方法getId()没有该脚本的throws声明)
在构造函数之后我创建了异常(在类UNGraph中):
public class NoSuchElementException extends Exception {
public NoSuchElementException(String message){
super(message);
}
}
这是除例外的方法
public int getId(....) throws NoSuchElementException {
if (condition is met) {
//Do method
return variable;
}
else{
throw new NoSuchElementException (message);
}
}
显然我不希望该方法每次都抛出异常,就在条件不满足时;当它满足时,我想返回一个变量.
解决方法
编译器发出错误,因为Java不允许您覆盖方法并添加已检查的Exception(任何扩展Exception类的用户定义的自定义异常).因为很明显你想要处理不满足某些条件作为意外事件(一个bug)的场景,你最好的选择就是抛出一个RuntimeException. RuntimeException(例如:IllegalArgumentException或NullPointerException)不必包含在方法签名中,因此您将减轻编译器错误.
我建议您对代码进行以下更改:
//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);
}