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:
An exception that is suppressed is not thrown. The method of suppression used depends on the version of Java the code is running on:
|
|
|
|