这段 Java Puzzlers 代码有什么问题?
What is wrong with this Java Puzzlers piece of code?
在 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 块捕获的异常(例如任何 RuntimeException
),out
甚至不会尝试关闭。
虽然在给定的示例中(使用 IOException
最有可能的普通流)这不是一个大问题,但代码不正确并且学习这样编写它可能会导致更严重的问题路.
在 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 块捕获的异常(例如任何 RuntimeException
),out
甚至不会尝试关闭。
虽然在给定的示例中(使用 IOException
最有可能的普通流)这不是一个大问题,但代码不正确并且学习这样编写它可能会导致更严重的问题路.