Try-With Resource when AutoCloseable is null

对着背影说爱祢 提交于 2019-12-09 07:23:28

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/35372148/try-with-resource-when-autocloseable-is-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!