在Java中,重寫方法時,能否將throws子句中宣告的異常型別從非檢查型異常改為檢查型異常?
檢查型異常是在編譯時發生的異常,也稱為編譯時異常。在編譯時不能簡單地忽略這些異常;程式設計師應該處理這些異常。
非檢查型異常是在執行時發生的異常,也稱為執行時異常。這些異常包括程式設計錯誤,例如邏輯錯誤或API的錯誤使用。在編譯時會忽略執行時異常。
非檢查型異常到檢查型異常
當超類中的方法丟擲非檢查型異常時,子類中重寫該方法不能丟擲檢查型異常。
示例
在下面的示例中,名為Super的類中有一個抽象方法,該方法丟擲非檢查型異常(ArithmeticException)。
在子類中,我們重寫了此方法並丟擲檢查型異常(IOException)。
import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Scanner; import java.io.InvalidClassException; abstract class Super { public abstract String readFile(String path) throws ArithmeticException; } public class ExceptionsExample extends Super { @Override public String readFile(String path) throws FileNotFoundException { // TODO Auto-generated method stub return null; } }
輸出
ExceptionsExample.java:12: error: readFile(String) in ExceptionsExample cannot override readFile(String) in Super public String readFile(String path) throws FileNotFoundException { ^ overridden method does not throw FileNotFoundException 1 error
但是,當超類中的方法丟擲檢查型異常時,子類中重寫該方法可以丟擲非檢查型異常。
示例
在下面的示例中,我們只是交換了超類和子類中方法的異常。
import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Scanner; import java.io.InvalidClassException; abstract class Super{ public abstract String readFile(String path) throws FileNotFoundException ; } public class ExceptionsExample extends Super { @Override public String readFile(String path) throws ArithmeticException { // TODO Auto-generated method stub return null; } }
如果編譯上面的程式,它會在沒有編譯時錯誤的情況下編譯。
輸出
Error: Main method not found in class ExceptionsExample, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application
廣告