In the new third edition of Effective Java, Joshua Bloch mentions a piece of code from Java Puzzlers (about closing resources in try-finally):
For starters, I was mistaken on page 88 of Java Puzzlers, and no one noticed for many years. In fact, two-thirds of the use of the close method in Java libraries was incorrect in 2007.
But I'm not sure which part is wrong here?
} 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
}
}
}
This is the new version of this code:
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();
}
source
share