受檢例外
與 RuntimeException 相反,所有受檢例外都必須有 try-catch 區塊,否則程式碼無法編譯,更別說執行。本練習中,你會看到必須在受檢例外外圍加入 try/catch,否則應用程式無法編譯也無法執行。
本練習屬於課程
Java 的資料型別與例外狀況
練習說明
- 先不做任何修改直接執行範例程式碼,你會發現呼叫
Class.forName()需要被處理;若未處理,會導致編譯錯誤(error: compilation failed)。 - 取消註解 try、catch,以及在 catch 區塊中顯示訊息的那行。
- 現在再次嘗試執行應用程式,你會看到因為已處理受檢例外,應用程式可以成功編譯並執行。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
public class CheckedExceptionHandling {
public static void main(String[] args) {
// Uncomment the try block
// try {
Class.forName("java.util.ArrayList");
// Uncomment the catch block for ClassNotFoundException
// } catch (ClassNotFoundException e) {
// Uncomment the message for the exception
// System.out.println("Work goes here to recover from the checked exception");
// Uncomment the end of the try/catch
// }
System.out.println("Work complete");
}
}