Exception 但非 RuntimeException,編譯器強制處理,代表可預期、可恢復的運行時情況(如 IO 錯誤、網絡超時)RuntimeException 或 Error,編譯器不強制處理,代表編程錯誤(如空指針、數組越界、參數非法)不應單純拋出或吞沒,而應在運行時嘗試恢復。示例:重試機制
public class Recover {
protected int current = 0;
protected boolean accept = false;
public void passing() throws NotBigEnoughException {
if (current > 2) accept = true;
else throw new NotBigEnoughException("reject " + current);
}
public static void main(String[] args) {
Recover re = new Recover();
while (!re.accept) {
try { re.passing(); }
catch (NotBigEnoughException e) {
System.out.println(e.getMessage());
re.current++; // 恢復動作:遞增嘗試
}
}
System.out.println("accept " + re.current);
}
}
// 輸出: reject 0 → reject 1 → reject 2 → accept 3
// 父類
public void passing() throws NotBigEnoughException { ... }
// 子類嘗試新增 UnknowException → 編譯錯誤
public void passing() throws NotBigEnoughException, UnknowException { ... } // 錯誤
// 方案一:內部捕獲並恢復,不再拋出
public void passing() {
while (!passed()) {
try { super.passing(); }
catch (NotBigEnoughException e) { increment(); }
}
}
// 方案二:新增方法 fortifiedPassing(),捕獲父類異常後按業務邏輯轉換
public void fortifiedPassing() throws NotBigEnoughException, UnknowException {
try { super.passing(); }
catch (NotBigEnoughException e) {
if (current >= 0) throw e;
else throw new UnknowException("unknown state: " + current);
}
}
main() 會自動打印堆棧並退出RuntimeException 拋出,調用鏈無需聲明 throws,由全局異常處理器統一記錄/展示public void fortifiedPassing() { // 無 throws 聲明
try { super.fortifiedPassing(); }
catch (NotBigEnoughException | UnknowException e) {
throw new RuntimeException(e); // 保留原始異常為 cause
}
}
// 調用者無需 try-catch,異常冒泡至頂層處理器
cause,保證診斷鏈完整