throws 與 throw 是 Java 異常機制中兩個易混淆的關鍵字,分別用於聲明與拋出異常。
public class Shoot {
static void pop() throws NegativeArraySizeException {
int[] arr = new int[-3]; // 運行時拋出 NegativeArraySizeException
}
public static void main(String[] args) {
try {
pop();
} catch (NegativeArraySizeException e) {
System.out.println("pop()方法拋出的異常:" + e.getMessage());
}
}
}
throws 聲明,或在 try-catch 中捕獲處理class MyException extends Exception {
private String message;
public MyException(String msg) { this.message = msg; }
@Override public String getMessage() { return message; }
}
public class Captor {
static int quotient(int x, int y) throws MyException {
if (y < 0) {
throw new MyException("除數不能是負數"); // 主動拋出
}
return x / y;
}
public static void main(String[] args) {
try {
int result = quotient(3, -1);
} catch (MyException e) {
System.out.println(e.getMessage()); // 除數不能是負數
} catch (ArithmeticException e) {
System.out.println("除數不能為0");
} catch (Exception e) {
System.out.println("其他異常:" + e.getMessage());
}
}
}
| 維度 | throws | throw |
|---|---|---|
| 位置 | 方法聲明 | 方法體內部 |
| 對象 | 異常類型(類) | 異常實例(new Exception()) |
| 語義 | 聲明「可能拋出」 | 動作「拋出」 |
| 配合 | 調用者 try-catch 或繼續 throws | 需 try-catch 捕獲或方法聲明 throws |
| 多異常 | 支持列表 | 單次拋出一個 |
throws 或 try-catch,否則編譯不通過throw new BusinessException(...),統一由全局異常處理器捕獲finally 中 throw 覆蓋原異常throw new RuntimeException("msg", cause) 保留根因