Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with this Java Puzzlers piece of code?

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();
}
like image 897
ctomek Avatar asked Jan 25 '18 17:01

ctomek


1 Answers

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.

like image 52
Kayaman Avatar answered Oct 11 '22 15:10

Kayaman