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.
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.
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.
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.
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.
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.
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