異常是阻止當前方法繼續執行的問題信號。Java 提供結構化異常處理機制,強制開發者面對錯誤,提升程序健壯性。
Throwable
├─ Error // 嚴重錯誤,不可恢復(OutOfMemoryError, StackOverflowError)
└─ Exception // 可處理的異常
├─ RuntimeException // 非受檢異常(NullPointerException, IllegalArgumentException)
└─ 其他 // 受檢異常(IOException, SQLException, ClassNotFoundException)
try {
// 可能拋異常的代碼
} catch (ExceptionType1 e) {
// 處理類型1
} catch (ExceptionType2 | ExceptionType3 e) { // Java 7+ 多捕獲
// 處理類型2/3
} finally {
// 無論是否異常必須執行(關流、釋放鎖)
}
throws Exception 在方法簽名聲明拋出受檢異常,調用者必須捕獲或繼續拋出。throw new Exception("msg") 手動拋出異常實例。RuntimeException 子類)無需聲明,但建議文檔說明。public static double divide() throws Exception {
Scanner sc = new Scanner(System.in);
System.out.print("輸入分子: ");
int a = Integer.parseInt(sc.nextLine());
System.out.print("輸入分母: ");
int b = Integer.parseInt(sc.nextLine());
if (b == 0) throw new ArithmeticException("分母不能為零");
return a / b;
}
public static void main(String[] args) {
try {
double result = divide();
System.out.println("結果: " + result);
} catch (NumberFormatException e) {
System.err.println("請輸入整數");
} catch (ArithmeticException e) {
System.err.println(e.getMessage());
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("程序結束");
}
}
public class BusinessException extends RuntimeException {
private final int code;
public BusinessException(int code, String msg) { super(msg); this.code = code; }
public int getCode() { return code; }
}
// 使用
if (user == null) throw new BusinessException(404, "用戶不存在");
catch (Exception e) 吞噬錯誤。AutoCloseable 資源。log.error("msg", e) 保留完整堆棧,避免 e.printStackTrace()。@throws 標註方法可能拋出的異常及觸發條件。