Reputation: 13344
My question is more of Why type than How.
I know that in Java 7 the following works:
try (
FileInputStream in = new FileInputStream(source);
FileOutputStream out = new FileOutputStream(target);
) {
.....................
} catch (......) {
...............
}
And the following gives a syntax error:
FileInputStream in;
FileOutputStream out;
try (
in = new FileInputStream(source);
out = new FileOutputStream(target);
) {
.....................
} catch (......) {
...............
}
I'm curious why is it so important for Closable
/Autoclosable
references to be local to the try
block? Is it just the logic that if we didn't own it than it's dangerous to close?
Upvotes: 3
Views: 3460
Reputation: 234847
I don't have a reference for this language design decision, but I think the issue is that allowing non-local variables to be autoclosed would be dangerous—that is, it would allow many unsafe coding styles. From the Java Language Specification:
A resource declared in a ResourceSpecification is implicitly declared final (§4.12.4) if it is not explicitly declared final.
If the resources were not final
, then inside the try
block they might be reassigned, resulting in resource leaks. Since they are (implicitly or explicitly) final
, the compiler would have to do a lot of extra work to ensure that the variables were definitely unassigned at the point the try
resource specification was entered. It would probably also require changes to the compiler semantics of final
, since the variables really should not have a valid value after the try
block exits; certainly not the value assigned to them in the try
resource specification. The cleanest (perhaps only) thing to do is to make the variables go out of scope when the try
block exits.
Upvotes: 7