【发布时间】:2018-07-05 01:39:42
【问题描述】:
在新的第三版 Effective Java Joshua Bloch 中提到了 Java Puzzlers 中的一段代码(它是关于在 try-finally 中关闭资源):
对于初学者,我在 Java Puzzlers 的第 88 页上弄错了,多年来没有人注意到。事实上,2007 年 Java 库中关闭方法的使用有三分之二是错误的。
但我不确定这里的哪一部分错了?
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ex) {
// There is nothing we can do if close fails
}
}
if (out != null) {
try {
out.close();
} catch (IOException ex) {
// Again, there is nothing we can do if close fails
}
}
}
这是这段代码的新版本:
try {
OutputStream out = new FileOutputStream(dst);
try {
byte[] buf = new byte[BUFFER_SIZE];
int n;
while ((n = in.read(buf)) >= 0) out.write(buf, 0, n);
} finally {
out.close();
}
} finally {
in.close();
}
【问题讨论】:
-
这几天新版本也出错了。一般来说,我们应该改用
try-with-resources。try-with-resources在抛出多个异常时有更全面的处理。例如,在 Bloch 的第二个示例中,如果in.close()和out.close()都抛出异常,则从out.close()抛出的异常将永远丢失,但try-with-resourcesadds it to the suppressed exceptions。 docs.oracle.com/javase/tutorial/essential/exceptions/… -
@Radiodef 是的,try-with-resources 是推荐的解决方案,我只是想确定在这个 pre-try-with-resources 世界中出了什么问题。
标签: java try-catch try-catch-finally effective-java try-finally