異常是程序運行過程中違背預期的事件。Java 通過異常處理機制,將錯誤檢測、傳播、處理分離,保證程序健壯性。本文系統梳理異常捕獲、拋出、自定義異常的核心語法與最佳實踐。
try {
// 可能拋出異常的代碼
} catch (ExceptionType e) {
// 異常處理邏輯
} finally {
// 無論是否異常必執行的清理代碼(關流、釋放資源)
}
public static void main(String[] args) {
int divisor = 0;
double result = 0;
try {
System.out.println("請輸入非零數字:");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
divisor = Integer.parseInt(input); // 可能拋 NumberFormatException
result = 100 / divisor; // 可能拋 ArithmeticException
System.out.println("結果:" + result);
} catch (Exception e) {
System.out.println("輸入錯誤:" + e.getMessage());
}
}
輸入 "abc" 觸發 NumberFormatException,輸入 "0" 觸發 ArithmeticException,統一由 catch 捕獲處理。
聲明方法可能拋出的受檢異常,強制調用者處理:
public static double divide() throws Exception {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
int num = Integer.parseInt(input);
return 100 / num;
}
// 調用處必須 try-catch 或繼續 throws
public static void main(String[] args) {
try {
System.out.println(divide());
} catch (Exception e) {
System.out.println("計算失敗");
}
}
在代碼邏輯中主動拋出特定異常:
if (input.equals("abc")) {
throw new NumberFormatException("禁止輸入 abc");
}
| 維度 | throws | throw |
|---|---|---|
| 位置 | 方法聲明處 | 方法體內部 |
| 含義 | 聲明可能拋出的異常類型 | 實際拋出異常對象 |
| 執行 | 不一定發生 | 執行即拋出 |
| 處理責任 | 推給調用者 | 當前方法或調用者 |
// 1. 自定義異常
class DivideByZeroException extends Exception {
public DivideByZeroException(String msg) { super(msg); }
}
// 2. 業務方法拋出
class Calculator {
public int div(int a, int b) throws DivideByZeroException {
if (b == 0) throw new DivideByZeroException("除數不能為零");
return a / b;
}
}
// 3. 調用處理
public static void main(String[] args) {
try {
System.out.println(new Calculator().div(10, 0));
} catch (DivideByZeroException e) {
System.err.println(e.getMessage()); // 除數不能為零
e.printStackTrace();
}
}
異常機制非單純錯誤處理,更是控制流的一種表達方式。善用它,讓錯誤路徑如主流程般清晰可控。