我正在用java中的方法覆盖来练习异常处理机制......我的代码如下:
class base {
void show() {
System.out.println("in base class method");
}
}
class derived extends base {
void show() throws IOException {
System.out.println("in derived class method");
throw new IOException();
}
}
class my {
public static void main(String[] args) {
try {
base b = new derived();
b.show();
}
catch (IOException e) {
System.out.println("exception occurred at :" + e);
}
}
}
显示错误:
所以,我更正了以下内容:
void show() throws IOException{
它工作正常......
我又做了一个实验:
void show() throws Exception{
但它也显示错误:
据我了解,这是因为重写方法的子句应该在超类方法的子句中throws
提及确切的检查异常。throws
与第二种情况一样,如果我在 throws 子句中编写IOException
的超类Exception
,它也会显示错误。为什么?即使Exception
是所有异常的父类。
我刚刚尝试过......这个错误告诉我什么我不知道......
任何人都可以解释它所说的内容以及在throws
覆盖方法的子句中提及检查异常的约束是什么?