What are the precedence rules for try-with-resource
construct? Here is an example (note: all the mentioned classes implement Closeable
):
try (Page closeablePage = page;
PipedOutputStream out = outs;
SequenceWriter sequenceWriter = mapper.writer().writeValuesAsArray(out)) {
// do stuff
} finally {
callback.run();
}
When is the callback run? My assumptions is:
SequenceWriter
PipedOutputStream
Page
Am I wrong here?
In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.
The try -with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try -with-resources statement ensures that each resource is closed at the end of the statement.
Yes, It is possible to have a try block without a catch block by using a final block. As we know, a final block will always execute even there is an exception occurred in a try block, except System. exit() it will execute always.
For try-with-resources, if an exception is thrown in a try block and in a try-with-resources statement, then the method returns the exception thrown in the try block. The exceptions thrown by try-with-resources are suppressed, i.e. we can say that try-with-resources block throws suppressed exceptions.
The finally
block will be run after all resources have been closed by the try-with-resources
statement.
This is specified in the JLS section 14.20.3.2, quoting:
Furthermore, all resources will have been closed (or attempted to be closed) by the time the finally block is executed, in keeping with the intent of the finally keyword.
Additionally, all resources are closed in reverse declaration order. Quoting section 14.20.3 (emphasis mine):
Resources are closed in the reverse order from that in which they were initialized. A resource is closed only if it initialized to a non-null value. An exception from the closing of one resource does not prevent the closing of other resources. Such an exception is suppressed if an exception was thrown previously by an initializer, the try block, or the closing of a resource.
This means your assumption is correct.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With