繁体   English   中英

重写的方法不会引发异常

[英]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类的任何用户定义的自定义异常)。 因为很明显,您要处理满足某些条件的情况(意外发生)(错误),所以最好的选择是抛出RuntimeException RuntimeException (例如: 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);
}

当使用类和接口编写如下代码时,问题就变得很明显:

Graph g = new UNGraph();
int id = g.getId(...);

Graph接口没有声明它抛出了被检查的异常NoSuchElementException ,因此编译器将允许此代码在没有任何代码的情况下使用try块或throws子句。但是,重写方法显然可以抛出被检查的异常; 它已经宣布了很多。 这就是为什么覆盖方法不能抛出比覆盖方法或抽象方法更多的检查异常的原因。 根据对象的实际类型,调用代码需要如何处理检查的异常会有差异。

让接口的方法声明声明它抛出NoSuchElementException或者让实现类的方法自己处理NoSuchElementException

如果要让子类在该方法中引发检查的异常,则必须在所有超类中为throws NoSuchElementException检查的异常声明throws NoSuchElementException

您可以在Java Language Specification中阅读更多内容:

11.2。 编译时检查异常

Java编程语言要求程序包含用于检查异常的处理程序,这些异常可能是由于执行方法或构造函数而导致的。 对于每个可能的结果检查异常,方法(第8.4.6节 )或构造函数(第8.8.5节 )的throws子句必须提及该异常的类或该异常的类的超类之一( 第§ 11.2.3 )。

这种检查异常处理程序是否存在的编译时检查旨在减少未正确处理的异常的数量。 throws子句中命名的已检查异常类(第11.1.1节 )是方法或构造函数的实现者与用户之间的契约的一部分。 重写方法的throws子句可能不指定此方法将导致抛出任何检查的异常,而该异常将由其throws子句不允许抛出该覆盖的方法(第8.4.8.3节 )。


当我在使用它时,您可能不应该使用NoSuchElementException ,因为它在JRE中使用了……请使用其他名称。

这里 “异常与方法覆盖在Java中处理”就是答案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM