微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 重写方法不会抛出异常

编译我的代码时遇到问题,我试图让一个类的方法抛出一个个性化的异常,给定一些条件.但在编译时我得到的信息是:

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);
}

原文地址:https://www.jb51.cc/java/129479.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐