Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try-with-resource vs finally precedence

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:

  1. closing the SequenceWriter
  2. closing the PipedOutputStream
  3. closing the Page
  4. running the callback

Am I wrong here?

like image 647
Jiri Kremser Avatar asked Oct 06 '15 09:10

Jiri Kremser


People also ask

Does try-with-resources close before finally?

In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.

What is the difference between try and try-with-resources?

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.

Can try-with-resources exist without catch and finally?

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.

Does try-with-resources Throw exception?

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.


1 Answers

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.

like image 171
Tunaki Avatar answered Oct 02 '22 14:10

Tunaki