java - 重写的方法不会抛出异常

标签 java exception methods overriding

我在编译我的代码时遇到了问题,我正在尝试让一个类的方法在给定一些条件的情况下抛出一个个性化的异常。但在编译时我收到消息:

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 类的用户定义的自定义异常)。因为您显然希望将某些条件满足的情况视为意外事件(错误),所以您最好的选择是抛出 RuntimeExceptionRuntimeException,例如:IllegalArgumentExceptionNullPointerException,不必包含在方法签名中,因此您可以减少编译器错误。

我建议对您的代码进行以下更改:

//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/

相关文章:

Java swing - 多个控件的相同处理程序

java - 修改ArrayList的ArrayList时并发修改异常

java - 当代码不使用 git 时,Eclipse 中出现 Git 异常

Java泛型方法

objective-c - Iphone:在单独的文件中编写一些方法以便从任何地方访问

java - 两个线程获得相同的值

java - 开发中如何避免在编译时浪费时间?

java - 阻止 Android Activity 因区域设置更改而被破坏

c# - 是什么阻止我的事件处理程序方法完成?

java - 接受用户输入的方法