本文通過具體代碼示例,詳細講解 Java 異常捕獲、拋出、方法簽名聲明、調用鏈傳遞以及運行時異常與受檢異常的區別。
try 監控區塊,catch 捕獲處理,finally 保證執行清理代碼。import java.util.Scanner;
public class ExceptionDemo {
public static void main(String[] args) {
int num = 0;
double result = 0;
try {
System.out.print("請輸入非零整數: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
num = Integer.parseInt(input); // 可能拋 NumberFormatException
result = 100 / num; // 可能拋 ArithmeticException
System.out.println("結果: " + result);
} catch (NumberFormatException e) {
System.out.println("輸入非整數");
} catch (ArithmeticException e) {
System.out.println("分母不能為零");
} catch (Exception e) {
System.out.println("未知錯誤: " + e.getMessage());
}
}
}
方法簽名加 throws Exception,將處理責任推給調用者。
public class ThrowDemo {
public static double readAndDivide() throws Exception {
Scanner sc = new Scanner(System.in);
System.out.print("請輸入非零整數: ");
String input = sc.nextLine();
int num = Integer.parseInt(input); // 拋 NumberFormatException
return 100 / num; // 拋 ArithmeticException
}
public static void main(String[] args) {
try {
double res = readAndDivide();
System.out.println("結果: " + res);
} catch (Exception e) {
System.out.println("捕獲到異常: " + e.getClass().getSimpleName());
}
}
}
| 維度 | 受檢異常 (Checked) | 非受檢異常 (Unchecked) |
|---|---|---|
| 繼承 | Exception (非 RuntimeException) | RuntimeException、Error |
| 編譯檢查 | 強制捕獲或聲明 throws | 不強制 |
| 典型例子 | IOException、SQLException、ClassNotFoundException | NullPointerException、IllegalArgumentException、ArithmeticException |
| 適用場景 | 外部資源失敗、業務邏輯可預期錯誤 | 編程錯誤、不可恢復的系統級故障 |
catch (Exception e) 吞噬錯誤。RuntimeException,攜帶錯誤碼、提示信息,便於統一異常處理器(@ControllerAdvice)返回友好響應。try-with-resources 自動關閉資源。log.error("msg", e)。