Try-With Resource when AutoCloseable is null

JavaTry CatchAutocloseable

Java Problem Overview


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();
}

Java Solutions


Solution 1 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionflakesView Question on Stackoverflow
Solution 1 - JavaAndy ThomasView Answer on Stackoverflow