P45 Imminent P45 Imminent - 3 months ago 8
Java Question

Possible null pointer exception on autocloseable idiom

Consider the following try-with-resources block:

try (Foo foo = getAFoo()) {

}


For some class
Foo
that implements
java.lang.AutoCloseable
.

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

Answer

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).

Comments