应该将 .close() 放在 finally 块中吗?
原文地址:http://www.programcreek.com/2013/12/should-close-be-put-in-finally-block-or-not/
以下是关闭输出程序的 3 种不同方法。 第一个在 try 子句中放置 close() 方法,第二个放在 finally 子句中,第三个使用 try-with-resources 语句,其中哪一个是正确的或最好的?
//close() is in try clause
try {
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter("out.txt", true)));
out.println("the text");
out.close();
} catch (IOException e) {
e.printStackTrace();
}
//close() is in finally clause
PrintWriter out = null;
try {
out = new PrintWriter(
new BufferedWriter(
new FileWriter("out.txt", true)));
out.println("the text");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
//try-with-resource statement
try (PrintWriter out2 = new PrintWriter(
new BufferedWriter(
new FileWriter("out.txt", true)))) {
out2.println("the text");
} catch (IOException e) {
e.printStackTrace();
}
答案:
因为 Writer 在异常或者没有异常的情况下都应该被关闭,所以 close() 应该被放在 finally 子句中。
而从 Java 7 开始,我们可以使用 try-with-resources 语句。