What is wrong with this piece of Java Puzzlers code?

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();
}
+4
source share
1 answer

If an in.close()exception is thrown that is not caught by a catch block (for example, any RuntimeException), outit will not even try to be closed.

( , IOException ), , , .

+7

Source: https://habr.com/ru/post/1692726/


All Articles