请在下面找到我的代码,我想清除我关于覆盖和抛出异常的概念。下面提供的代码是否有效,如果是,那为什么。?我问这个问题是因为 IOException 和 ArithmeticException 之间没有直接的父子关系。
public class TestExceptionChild {
public static void main(String[] args) {
Parent parent = new Child();
try {
parent.msg();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Parent{
void msg() throws IOException{
System.out.println("parent");
}
}
class Child extends Parent{
void msg() throws ArithmeticException{
System.out.println("child");
}
}
最佳答案
这会起作用,但只是因为 ArithmeticException
扩展了 RuntimeException
(即它不是检查异常,所以使用 throws
子句这里是不必要的)。如果您使用检查异常而不是 ArithmeticException
,则它必须是或扩展类型 IOException
。否则,你会得到一个编译错误。
所以要回答您的问题,是的,层次结构对于checked 异常很重要。参见 here了解更多详情。
关于java - 父子层次结构在重写时对抛出很重要吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40452554/