覆盖方法可以抛出Java中被覆盖方法抛出的异常的超类型吗?
如果超类方法抛出某些异常,则子类中的方法不应抛出其超类型。
示例
在下面的示例中,超类的readFile()方法引发FileNotFoundException异常,子类的readFile()方法引发IOException,这是FileNotFoundException的超类型。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
abstract class Super {
public String readFile(String path)throws FileNotFoundException {
throw new FileNotFoundException();
}
}
public class ExceptionsExample extends Super {
@Override
public String readFile(String path)throws IOException {
//method body ......
}
}编译时错误
在编译时,上述程序为您提供以下输出-
ExceptionsExample.java:13: error: readFile(String) in ExceptionsExample cannot override readFile(String) in Sup
public String readFile(String path)throws IOException {
^
overridden method does not throw IOException
1 error热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短