構造器中途拋出異常時,已獲取資源(如開啟文件)需清理,但 finally 會在構造器正常結束時也執行,導致過早釋放。
class InputFile {
private BufferedReader in;
InputFile(String fname) throws Exception {
try {
in = new BufferedReader(new FileReader(fname));
} catch (FileNotFoundException e) {
throw e; // 尚未開啟,無需關閉
} catch (Exception e) {
try { in.close(); } catch (IOException ignored) {}
throw e;
}
// finally 不關閉,避免正常結束時釋放
}
String getLine() { ... }
void cleanup() { try { in.close(); } catch (IOException ignored) {} }
}
InputFile in = new InputFile("test.txt");
try {
while ((line = in.getLine()) != null) ...
} finally {
in.cleanup(); // 確保釋放
}
FileNotFoundException 單獨捕獲,因資源未獲取。finalize()(不可靠),採用顯式 cleanup() 模式。