简体   繁体   中英

Possible null pointer exception on autocloseable idiom

Consider the following try-with-resources block:

try (Foo foo = getAFoo()) {

}

For some class Foo that implements java.lang.AutoCloseable .

If getAFoo() were to return null , then would a null pointer exception be thrown on the closing brace (due to the runtime attempting to call close )?

According to this Oracle blog :

After due consideration the JSR 334 expert group has decided the semantics of the try-with-resources statement on a null resource should be changed as follows: the compiler-generated calls to close a resource will only occur if the resource is non-null.

This means that you can close any null resource in a try (with resources) block without throwing an error (and the same when the program automatically tries to close the resource when the try ends).

You implement java.lang.AutoCloseable , so the compiler wil try to close resource when done, but process to close a resource will only occur if the resource is non-null . So in this case I think no exception will be thrown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM