Why doesn't try-with-resources work with field variables?

An instance variable may be changed at any point during the execution of the try-with-resources block. This would break its invariant and prevent the cleanup. Note that the local variable is implictly final, for the same reason.

BTW a better question is, why does Java force us to declare a local variable, even if we don't refer to it within the block. C#, for example, doesn't require this.

Update: with version 9, Java has stopped forcing us:

private Some obj = new Some();

try (obj) { 
  // obj captured in a hidden local variable, resource closed in the end
}

I suspect the designers considered using a field a bad idea as this allow the object to escape the region of usage. i.e. it is only valid in the try block so you shouldn't be able to access it anywhere else.


Section 14.20.3 of the Java Language Specification states it will only work with local variables.

Why is this? My guess is checking for definite assignment and escapage (the local variable doesn't escape into the scope of another method). A field may be initialized anywhere in the class. My guess is that by validating it's a local variable, it's much simpler to analyse.