Upcoming change in semantics to try-with-resources on a null resource
Joe Darcy
joe.darcy at oracle.com
Wed Feb 16 15:06:04 PST 2011
Hello.
After due consideration the JSR 334 expert group has decided the
semantics of the try-with-resources statement on a null resource should
be changed as follows: the compiler-generated calls to close a resource
will only occur if the resource is non-null.
Concretely, the semantics of the desugaring of the finally block are
changed from
finally {
if (#primaryException != null) {
try {
#resource.close();
} catch(Throwable #suppressedException) {
#primaryException.addSuppressed(#suppressedException);
}
} else {
#resource.close();
}
}
to
finally {
if (#primaryException != null) {
try {
if(#resource != null)
#resource.close();
} catch(Throwable #suppressedException) {
#primaryException.addSuppressed(#suppressedException);
}
} else {
if(#resource != null)
#resource.close();
}
}
This decision was informed by discussions on coin-dev as well as
experiments retrofitting try-with-resources onto the JDK libraries.
The change allows idioms like
try(Resource r = methodThatMightReturnNull()) {
if (r == null)
return; // nothing to do
}
to complete normally without generating a null pointer exception. Note
that the programmer still has responsibility to check for a null
resource if the resource is used inside the try block; the generated
null check does *not* occur before the try block is entered.
Implementing the change is being tracked under Oracle bug 7020047
"Project Coin: generate null-check around try-with-resources close call."
Thanks for the feedback; cheers,
-Joe
More information about the coin-dev
mailing list