try-with-resources and null resource

Rémi Forax forax at univ-mlv.fr
Wed Jan 26 05:58:14 PST 2011


On 01/25/2011 07:09 PM, Tim Peierls wrote:
> On Tue, Jan 25, 2011 at 12:40 PM, Rémi Forax <forax at univ-mlv.fr 
> <mailto: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

Again, your talking about implementation of the construct and not 
semantics of the construct.
Perhaps, it's because try-with-resources reuses the same keyword as 
try/finally which doesn't help.

try-with-resources is a new construct of the language, the question is 
what should this construct do
if the resource is null.

To make things crystal-clear, what should you be the semantics of:
using(R r = get()) {
   maybeUse(r);
}
if get() returns null.

Rémi





More information about the coin-dev mailing list