try-with-resources and null resource

Tim Peierls tim at peierls.net
Tue Jan 25 10:09:30 PST 2011


On Tue, Jan 25, 2011 at 12:40 PM, Rémi Forax <forax at univ-mlv.fr> wrote:

> All cited construct including try() may dereference a value hence throw a
> NPE.
>
> switch(null) can jump to default or at the end of the switch block, if
> there is no default.
> for(Object o:null) { } can do not execute its body.
> synchronized(null) can synchronized to a special token.
> try(Object o = null) { } can do not execute its body
>
> But for switch, for and synchronized it was chosen to throw a NPE.
>

This is a misleading analogy. The thing that a resource declaration most
resembles is not try, switch, for, or synchronized, but an ordinary variable
declaration with initializer.

This code doesn't throw NPE when initializing r with null:

R r = get();
try {
    maybeUse(r);
} finally {
    r.close();
}

Nor should this code:

try (
    R r = get();
) {
    maybeUse(r);
}

--tim



More information about the coin-dev mailing list