Java中重写方法是否可以抛出被重写方法抛出的异常的超类型?

javaobject oriented programmingprogramming更新于 2024/6/29 21:30:00

如果超类方法抛出某些异常,子类中的方法不应抛出其超类型。

示例

在下面的例子中,超类的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 {
      //方法主体 ......
   }
}

编译时错误

编译时,上述程序会给出以下输出−

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

相关文章