Try-With Resource when AutoCloseable is null

时间:2016-02-12 21:04:45

标签: java try-catch autocloseable

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

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

close

1 个答案:

答案 0 :(得分:45)

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.

undefined method `find_total_by_user_object_and_year' for #<Class:0x007fb7551514e0>

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.

相关问题