Please: try-with-resouces Lock support!

Neal Gafter neal at
Sat Mar 5 12:18:31 PST 2011

In the try-with-resource language construct, exceptions thrown during the
construction of the resource are caught in the catch clauses.  Therefore,
making the resource in scope be within the catch clause would be providing
access to a variable that is not definitely assigned.  Since a variable that
is final (by the try-with-resources specification), not definitely assigned
(because the exception might have occurred during the resource expression),
and not definitely unassigned (because the exception might have occurred
during the try block), it cannot be used in any way.  There is therefore no
point in making the variable be in scope within the catch clause.

The correct thing to do is Stephen' suggestion:

On Sat, Mar 5, 2011 at 11:08 AM, Stephen Colebourne <scolebourne at>wrote:

> But there is a "hack" solution:
> try(Resource r  = getResource()) {try {
>     doSomething(r);
> } catch (ResourceException e) {
>    System.out.println(e + " from " + r); // r undefined here
> }}
> Not ideal.

This is the correct solution, and it is both ideal and not a hack.  I'm not
sure I agree with your spacing and placement of curly braces, but that is a
style issue.  The semantics of this code are different (than a catch on the
try-with-resources statement) because the catch clause here only catches
exceptions thrown from within the inner try block.  If you want to use the
resource variable, that is exactly what you need.

At worst, this exchange demonstrates that the try-with-resources
specification is piling too much complexity on the already overly complex
try statement.


More information about the coin-dev mailing list