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 final Some obj = new Some();

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)