Try-With Resource when AutoCloseable is null

前端 未结 1 1644
夕颜
夕颜 2021-02-06 20:48

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

I assumed this would lead to a null pointer excep

相关标签:
1条回答
  • 2021-02-06 21:00

    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.

    0 讨论(0)
提交回复
热议问题