Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 339
P45 Imminent Avatar asked Nov 13 '15 12:11

P45 Imminent


People also ask

How do I fix NullPointerException could be thrown?

NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.

What is possible null pointer dereference?

CWE-476: NULL Pointer Dereference: A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.

Can NullPointerException be caught?

Programmers typically catch NullPointerException under three circumstances: The program contains a null pointer dereference. Catching the resulting exception was easier than fixing the underlying problem. The program explicitly throws a NullPointerException to signal an error condition.


1 Answers

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

like image 184
Jonathan Lam Avatar answered Sep 22 '22 09:09

Jonathan Lam