use*_*551 8 java methods overriding exception
在编译我的代码时遇到问题,我试图让一个类的方法抛出一个个性化的异常,给定一些条件.但在编译时我得到的信息是:
重写方法不会抛出异常
这是类和异常声明:
public class UNGraph implements Graph
Run Code Online (Sandbox Code Playgroud)
Graph是一个包含其中所有方法的接口UNGraph(该方法getId()没有throws该脚本的声明)
在构造函数之后我创建了异常(在类UNGraph中):
public class NoSuchElementException extends Exception {
public NoSuchElementException(String message){
super(message);
}
}
Run Code Online (Sandbox Code Playgroud)
这是除例外的方法
public int getId(....) throws NoSuchElementException {
if (condition is met) {
//Do method
return variable;
}
else{
throw new NoSuchElementException (message);
}
}
Run Code Online (Sandbox Code Playgroud)
显然我不希望该方法每次都抛出异常,就在条件不满足时; 当它满足时,我想返回一个变量.
Sea*_*key 12
编译器发出错误,因为Java不允许您覆盖方法并添加已检查的Exception(任何扩展Exception该类的用户定义的自定义异常).因为它要处理,其中的一些条件,该方案显然不能满足作为一个意外的发生(错误),你最好的选择就是抛出RuntimeException.A 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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15300 次 |
| 最近记录: |