java中方法和构造函数中异常的继承

时间:2016-05-11 08:09:42

标签: java exception inheritance

我有代码:

class Father {
public Father() throws IOException {}
public void foo() throws IOException {}
}

class Child extends Father {
//If use FileNotFoundException here, compile fail
public Child() throws Exception {}  

//If use Exception here, compile fail
public void foo() throws FileNotFoundException {}
}

在编写child的构造函数时,我们必须至少抛出父的构造函数或超级异常(IOException - > Exception)的异常。 但是,对于child的方法,它必须抛出子异常(IOException - > FileNotFoundException)。 为什么它出现在Java中。请解释一下? 感谢

2 个答案:

答案 0 :(得分:4)

如果覆盖方法并且不调用super方法,则可以缩小异常

public class Child {
    public void foo() throws FileNotFoundException {
         // overrides Parent.foo() throws IOException
    }
}

但是在构造函数的情况下,插入了对父构造函数的隐式super()调用,因此子构造函数也必须至少声明父构造函数的所有已检查异常。

答案 1 :(得分:2)

根据您的代码,您的问题看起来有两个部分,答案如下 -

  1. 对于构造函数,您必须指定更广泛或相同级别的已检查异常。对于未经检查的例外,情况就不同了。

  2. 重写方法不应抛出新的或更广泛的异常,而不是重写方法声明的异常。