覆蓋方法能否丟擲 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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP