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

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.

Leave a Comment