Try-With Resource when AutoCloseable is null

flakes picture flakes · Feb 12, 2016 · Viewed 12.3k times · Source

How does the try-with feature work for AutoCloseable variables that have been declared null?

I assumed this would lead to a null pointer exception when it attempts to invoke close on the variable, but it runs no problem:

try (BufferedReader br = null){
    System.out.println("Test");
}
catch (IOException e){
    e.printStackTrace();
}

Answer

Andy Thomas picture Andy Thomas · Feb 12, 2016

The Java Language Specification specifies that it is closed only if non-null, in section 14.20.3. try-with-resources:

A resource is closed only if it initialized to a non-null value.

This can actually be useful, when a resource might present sometimes, and absent others.

For example, say you might or might not have a closeable proxy to some remote logging system.

try ( IRemoteLogger remoteLogger = getRemoteLoggerMaybe() ) {
    if ( null != remoteLogger ) {
       ...
    }
}

If the reference is non-null, the remote logger proxy is closed, as we expect. But if the reference is null, no attempt is made to call close() on it, no NullPointerException is thrown, and the code still works.