In new, third edition of Effective Java Joshua Bloch mentions piece of code from Java Puzzlers (it's about closing resources in 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.
But I am 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 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();
}
If in.close()
throws an exception not caught by the catch block (such as any RuntimeException
), out
won't be even tried to be closed.
While in the given example (with normal streams where IOException
would be most likely) it's not a huge issue, the code is not correct and learning to write it like that could cause more serious issues down the road.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With