Throwable
├── Error // JVM 級嚴重錯誤,不捕獲(OOM、StackOverflow)
└── Exception
├── RuntimeException (Unchecked) // 編程 Bug,可不處理(NPE、IndexOutOfBounds)
└── Checked Exception // 外部風險,強制處理(IOException、SQLException)
try {
System.out.println(ints[4]); // 拋出 IndexOutOfBoundsException
System.out.println("我還有幸執行到嗎"); // 不會執行
} catch (IndexOutOfBoundsException e) {
System.out.println("數組越界錯誤");
} finally {
System.out.println("異常出現後"); // 必定執行
}
// 輸出:異常出現前 → 數組越界錯誤 → 異常出現後
無 try-catch 時,異常直接沿調用棧拋出,後續代碼不再執行。
try {
new BufferedInputStream(new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
throw e; // 原封不動拋給上層,保持堆棧軌跡
}
try { f(); }
catch (ExceptionB e) {
ExceptionC c = new ExceptionC("新異常");
c.initCause(e); // 關鍵:建立因果鏈
throw c;
}
// 輸出包含 "Caused by: ExceptionB",便於根因定位
模式一:try-finally(JDK 6 及之前)
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
// 業務邏輯
} finally {
if (reader != null) try { reader.close(); } catch (IOException ignore) {}
}
模式二:try-with-resources(JDK 7+ 推薦)
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
// 業務邏輯
} // 編譯器自動生成 finally 關閉資源,支援多資源
構造器開啟資源場景:提供 dispose() 方法,調用方負責在 finally 中調用。
e.printStackTrace() 非業務處理。原則:記錄上下文、拋轉業務異常、或實際恢復。catch (Exception e) {} 空塊。嚴禁,至少記錄日誌。