我对例外情况有些怀疑。
谁能告诉我为什么Java不允许我们在子类中创建Checked Exception,而Java却允许子类中Unchecked异常
下面的示例在我使用'throws IOException'时抛出编译时错误,但是当我在子类中使用'throws ArithmeticException'时它不会抛出任何错误。
这是代码(您将获得编译时错误)
package com.exception.test;
import java.io.IOException;
public class Parent {
void msg() {
System.out.println("Parent...");
}
public static void main(String[] args) {
Parent parent = new Child();
parent.msg();
}
}
class Child extends Parent {
void msg() throws IOException {
System.out.println("Child...");
}
}
//使用unCheckedException
package com.exception.test;
import java.io.IOException;
public class Parent {
void msg() {
System.out.println("Parent...");
}
public static void main(String[] args) {
Parent parent = new Child();
parent.msg();
}
}
class Child extends Parent {
void msg() throws ArithmeticException {
System.out.println("Child...");
}
}
最佳答案
如果子类方法声明它可以引发父类没有的已检查异常,则它会破坏Liskov substitution principle,这是面向对象编程的基石之一。
考虑以下这段代码,声明Child.msg
引发一个已检查的异常:
void doMsg(Parent p) {
p.msg();
}
如果传入子对象,则程序语义会中断,因为现在既不会捕获也不会抛出已检查的异常:不再“检查”该异常。
由于未经检查的异常可以在任何地方抛出,因此声明抛出异常没有其他目的。因此,可以安全地允许它。