Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is declaration required in Java's try-with-resource

Tags:

java

try-catch

Java7's try-with-resources is great and all, but I can't wrap my head around why it is required to include the declaration of the resource in the try statement. My gut says the following should be possible:

CloseableResource thing;
try (thing = methodThatCreatesAThingAndDoesSomeSideEffect()) {
    // do some interesting things
}
thing.collectSomeStats();

Alas, this results in a syntax error (cryptically expecting a ;). Moving the type definition/declaration into the try statement works, which of course moves thing into the corresponding scope. I can figure out how to work around this when I want more from my AutoClosable than getting closed, I'm interested in why the compiler requires it like this.

like image 259
akaIDIOT Avatar asked Dec 12 '12 09:12

akaIDIOT


People also ask

What is the purpose of a try with resources statement?

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.

What happens if try with resources throws an 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.

Does try with resources need finally?

In the try-with-resources method, there is no use of the finally block. The file resource is opened in try block inside small brackets. Only the objects of those classes can be opened within the block which implements the AutoCloseable interface, and those objects should also be local.

Can we use try with resources 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.


1 Answers

Since Java 9 you can declare and initialize the variable used inside try-with-resources outside the block. The only additional requirement for variable is that it has to be effectively final.
So now it is possible to do:

CloseableResource thing = methodThatCreatesAThingAndDoesSomeSideEffect();
try (thing) {
    // do some interesting things
}
thing.collectSomeStats();

Hope it helps.

like image 120
Michał Szewczyk Avatar answered Sep 23 '22 16:09

Michał Szewczyk