Is this pattern for handling IO exceptions in Java correct?

In the following code snippet, if ex1 is thrown, will be be caught by the second catch block, or will it be thrown back to the caller of the method?

And if it is thrown back to the caller, and then a second exception occurs in the finally block (ex2), does that mean 2 exceptions will be thrown back to the caller (ex1 and ex2)?

try {
  // write to file
} catch (IOException ex1) {
  throw ex1;
} finally {
  try {
    aBufferedWriter.close();
  } catch (IOException ex2) {
    throw ex2;
  }
}
Jon Skeet
people
quotationmark

Both of those exceptions would be thrown back to the caller... although a single exception in any particular situation. If the body of the outer try block throws and then close throws as well, only the second exception would be seen by the caller.

However, having a catch block just to rethrow is pointless. Your code would be clearer as:

try {
  // write to file
} finally {
  aBufferedWriter.close();
}

In Java 7, a try-with-resources statement can do that automatically:

try (BufferedWriter writer = new BufferedWriter(...)) {
    // Use the writer here
} // The writer is auto-closed here

That way you can also get at an exception on close separately from an exception in the main body, using Throwable.getSuppressed.

people

See more on this question at Stackoverflow