【问题标题】:Exception in overriding methods [duplicate]覆盖方法中的异常[重复]
【发布时间】:2013-11-24 08:52:27
【问题描述】:

继承类中的重写方法必须

与被覆盖的方法相比,抛出更少或更窄的异常,但不能抛出更广泛的异常。

我可以知道这条规则背后的意图吗?

【问题讨论】:

标签: java exception exception-handling


【解决方案1】:

子类必须能够像父类一样表现;当调用抛出(例如)IOExceptions 的父类方法时,您不会期望突然收到 OtherException

例如

public class ParentClass {


    public void doSomething() throws IOException{

    }
}


public class ChildClass extends ParentClass{

    @Override
    public void doSomething() throws IOException, CustomException{
        super.doSomething();
    }
}

当我们使用父类调用doSomething()时,我们有义务处理IO异常

public static void main(String[] args){
    ParentClass p=new ChildClass(); //child class behaving as parent
    try {
        p.doSomething();
    } catch (IOException ex) {
        Logger.getLogger(ChildClass.class.getName()).log(Level.SEVERE, null, ex);
    }//no catch for secret CustomException that the ChildClass can throw


}

但是你可以看到有一个秘密 CustomException 可以被抛出,我们还没有处理(但由于 CustomException 不是运行时异常,所以如果没有堆栈中较高的方法知道或处理它)

【讨论】:

    【解决方案2】:

    这意味着如果你重写一个抛出异常的方法,它只能抛出一个与超方法相同的异常,或者是从超类扩展异常的异常(如果你愿意,抛出更少)。

    【讨论】:

      【解决方案3】:

      被覆盖的方法不能抛出更新或更广泛的检查异常,因为当这个类的对象被多态引用时,调用者只能处理基类方法实现的契约中显示的异常.

      被覆盖的方法可能会抛出未经检查的异常,以防父方法抛出与否。您甚至可以不在签名中声明它。 但是如果父方法抛出检查异常,你只能在子方法中专门化这个异常(抛出相同的异常,它是后代或没有)。

      请参阅此链接以更好地理解:http://www.javatpoint.com/exception-handling-with-method-overriding

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-06
        • 2019-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-09
        • 2023-03-21
        相关资源
        最近更新 更多