【发布时间】:2018-11-06 06:11:58
【问题描述】:
在异常处理中,众所周知,如果超类方法不声明异常,子类重写的方法不能声明已检查异常,但可以声明未检查异常。为什么这样?考虑以下示例:
import java.io.*;
class Parent {
void msg() {
System.out.println("parent");
}
}
class TestExceptionChild extends Parent {
void msg() throws IOException {
System.out.println("TestExceptionChild");
}
public static void main(String args[]) {
Parent p = new TestExceptionChild();
p.msg();
}
}
我尝试过的:
我们在这里得到编译错误。如果我需要在重写方法“msg”中读取文件,那么我必须在此处提及“throws IOException”。但是java不允许它们。谁能解释一下?
【问题讨论】:
标签: exception-handling try-catch-finally