finally 區塊是 try-catch 結構的可選部分,無論是否發生異常、是否被捕獲、甚至 try 中有 return 語句,finally 都會在方法返回前執行。這特性使其成為釋放資源(關閉流、釋放鎖、斷開連線)的理想位置。
InputStream in = null;
try {
in = new FileInputStream("data.txt");
// 讀取操作
} catch (IOException e) {
log.error("讀取失敗", e);
} finally {
if (in != null) {
try { in.close(); } catch (IOException ignored) {}
}
}
Java 7 引入 try-with-resources 自動管理實現 AutoCloseable 的資源,簡化代碼:
try (InputStream in = new FileInputStream("data.txt")) {
// 讀取操作,自動關閉
}
注意:finally 中若拋出異常或執行 return,會覆蓋 try/catch 的返回值或異常,應避免在 finally 中使用 return 或拋出異常。