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?