java - Try-With Resource when AutoCloseable is null - Stack Overflow
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.
Read full article from java - Try-With Resource when AutoCloseable is null - Stack Overflow
No comments:
Post a Comment