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
)?
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With