我正在阅读有关继承和异常的内容。当我尝试在控制台中编译以下代码时,出现编译器错误。但我还是不明白为什么。但是如果我更改 B 类中的方法名称,一切都会正常。请帮忙。
这是我的代码:
import java.io.IOException;
class A {
public void print() throws IOException {
System.out.println("In Class A.");
throw new IOException("Printed in A.");
}
}
class B extends A {
public void print() throws Exception {
System.out.println("In Class B.");
throw new Exception("Printed in B.");
}
}
public class TestPrint {
public static void main (String args[]) {
B b = new B();
try {
b.print();
} catch (Exception e) {
e.printStackTrace();
}
}
}
最佳答案
重写的方法不能抛出层次结构高于原始方法的已检查异常。
Exception
是IOException
的父类(super class)。
因此,您的 print()
方法子类 (B
) 可以抛出 IOException
或 IOException 的任何子类
.
更改您的类B
,如下所示:
class B extends A {
public void print() throws IOException {
System.out.println("In Class B.");
throw new IOException("Printed in B.");
}
}
关于java - 程序未编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20158410/