我在编译我的代码时遇到了问题,我正在尝试让一个类的方法在给定一些条件的情况下抛出一个个性化的异常。但在编译时我收到消息:
Overridden method does not throw exception
这是类和异常声明:
public class UNGraph implements Graph
Graph
是一个接口(interface),里面有UNGraph
的所有方法(方法getId()
没有在该脚本上抛出
声明)
在构造函数之后我创建了异常(在 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
类的用户定义的自定义异常)。因为您显然希望将某些条件未满足的情况视为意外事件(错误),所以您最好的选择是抛出 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);
}
关于java - 重写的方法不会抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23526362/