我有代码:
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 {}
}
在编写子构造函数时,我们必须至少抛出父构造函数的异常或 super 异常(IOException -> Exception)。 但是,对于子方法,它必须抛出子异常(IOException -> FileNotFoundException)。 为什么会出现在Java中。请解释一下? 谢谢
最佳答案
如果您重写方法并且不调用 super 方法,则可能会缩小异常范围
public class Child {
public void foo() throws FileNotFoundException {
// overrides Parent.foo() throws IOException
}
}
但在构造函数的情况下,会插入对父构造函数的隐式 super()
调用,因此子构造函数还必须至少声明父构造函数的所有已检查异常。
关于java - java中方法和构造函数中异常的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37156650/