覆盖方法可以抛出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热门推荐
1 泰迪狗狗如何训练
3 狗狗训练图
5 狗狗训练方法
6 训练狗狗不咬人
8 敏捷训练狗狗
10 训练狗狗吃饭
11 泰迪狗狗训练
12 狗狗从多大开始训练
13 狗狗训练学校费用
14 怎么去训练狗狗
15 狗狗训练狗狗
16 狗狗训练教程
17 训练狗狗装死
18 泰迪狗狗的训练方法