在新的第三版 Effective Java 中,Joshua Bloch 提到了来自 Java Puzzlers 的一段代码(它是关于在 try-finally 中关闭资源):
For starters, I got it wrong on page 88 of Java Puzzlers, and no one noticed for years. In fact, two-thirds of the uses of the close method in the Java libraries were wrong in 2007.
但我不确定这里哪一部分是错误的?
} 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();
}
最佳答案
如果 in.close()
抛出未被 catch block 捕获的异常(例如任何 RuntimeException
),out
将不会甚至试图关闭。
虽然在给定的示例中(对于最有可能出现 IOException
的普通流)这不是一个大问题,但代码不正确并且学习这样编写它可能会导致更严重的问题路。
关于java - 这段 Java Puzzlers 代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48449093/