cto*_*mek 5 java try-catch try-catch-finally try-finally effective-java
在新的第三版Effective Java中,Joshua Bloch提到了Java Puzzlers的一段代码(它是关于在try-finally中关闭资源):
对于初学者来说,我在Java Puzzlers的第88页上弄错了,多年来没有人注意到.事实上,2007年Java库中close方法的三分之二使用是错误的.
但我不确定哪个部分错了?
} 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
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是此代码的新版本:
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();
}
Run Code Online (Sandbox Code Playgroud)
如果in.close()抛出一个未被catch块(例如any RuntimeException)捕获的异常,out则甚至不会尝试关闭.
虽然在给定的例子中(普通流IOException最有可能)但这不是一个大问题,但代码不正确并且学习如此编写它可能会导致更严重的问题.
| 归档时间: |
|
| 查看次数: |
274 次 |
| 最近记录: |