P45 Imminent P45 Imminent - 1 year ago 47
Java Question

Possible null pointer exception on autocloseable idiom

Consider the following try-with-resources block:

try (Foo foo = getAFoo()) {


For some class
that implements

were to return
, then would a null pointer exception be thrown on the closing brace (due to the runtime attempting to call

Answer Source

According to this Oracle blog:

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.

This means that you can close any null resource in a try (with resources) block without throwing an error (and the same when the program automatically tries to close the resource when the try ends).