| 特性 | Checked Exception | Runtime Exception |
|---|---|---|
| 繼承體系 | java.lang.Exception 子類(排除 RuntimeException) | java.lang.RuntimeException 或 Error 子類 |
| 方法宣告 | 必須 在 throws 列出 | 可省略 |
| 調用端處理 | 必須 try-catch 或繼續 throws | 可忽略,不強制捕獲 |
| 典型代表 | IOException, SQLException, MalformedURLException | NullPointerException, ArrayIndexOutOfBoundsException, IllegalArgumentException |
public class ExceptionDemo {
// Checked Exception:必須宣告
public void readFile(String path) throws IOException {
Files.readAllLines(Paths.get(path));
}
// Runtime Exception:無需宣告
public void parseInt(String s) {
Integer.parseInt(s); // 可能拋 NumberFormatException
}
// 傳遞 Checked Exception
public void processFile(String path) throws IOException {
readFile(path); // 未捕獲,向上拋出
}
}
調用端:
public static void main(String[] args) {
ExceptionDemo demo = new ExceptionDemo();
// 必須處理 Checked Exception
try {
demo.readFile("data.txt");
} catch (IOException e) {
e.printStackTrace();
}
// Runtime Exception 可不捕獲
demo.parseInt("abc"); // 運行時拋出 NumberFormatException
}
MalformedURLException —— 用戶輸入錯誤 URL,程式可提示重輸。ArrayIndexOutOfBoundsException —— 索引越界屬編碼錯誤,須修正代碼而非捕獲。SQLException)外洩到 Controller。@throws 明確說明拋出條件與含義。catch (Exception e) {} 是大忌,至少記錄日誌。Checked Exception 強制建立「異常契約」,適合可預期業務流程;Runtime Exception 守護程式正確性,暴露編碼缺陷。善用兩者分工,才能構建健壯、可維護的 Java 系統。