覆蓋方法能否丟擲 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

更新日期:15 年 10 月 2019 日

238 次瀏覽

開始你的 職業生涯

完成課程並獲得認證

開始吧
廣告
© . All rights reserved.