oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html"> try-with-resources statement in JDK6-compatible code. Running on Java 7, code using this should be approximately equivalent in behavior to the same code written with try-with-resources. Running on Java 6, exceptions that cannot be thrown must be logged rather than being added to the thrown exception as a suppressed exception.
This class is intended to be used in the following pattern:
{@code Closer closer = Closer.create();}try InputStream in = closer.register(openInputStream()); OutputStream out = closer.register(openOutputStream()); // do stuff } catch (Throwable e) { // ensure that any checked exception types other than IOException that could be thrown are // provided here, e.g. throw closer.rethrow(e, CheckedException.class); throw closer.rethrow(e); } finally { closer.close(); }}
Note that this try-catch-finally block is not equivalent to a try-catch-finally block using try-with-resources. To get the equivalent of that, you must wrap the above code in another try block in order to catch any exception that may be thrown (including from the call to {@code close()}).
This pattern ensures the following:
- Each {@code Closeable} resource that is successfully registered will be closed later.
- If a {@code Throwable} is thrown in the try block, no exceptions that occur when attemptingto close resources will be thrown from the finally block. The throwable from the try block will be thrown.
- If no exceptions or errors were thrown in the try block, the first exception thrown by an attempt to close a resource will be thrown.
- Any exception caught when attempting to close a resource that is not thrown (because another exception is already being thrown) is suppressed.
An exception that is suppressed is not thrown. The method of suppression used depends on the version of Java the code is running on:
- Java 7+: Exceptions are suppressed by adding them to the exception that will be thrown using {@code Throwable.addSuppressed(Throwable)}.
- Java 6: Exceptions are suppressed by logging them instead.
@author Colin Decker
@since 14.0