简体   繁体   English

autocloseable习语上可能的空指针异常

[英]Possible null pointer exception on autocloseable idiom

Consider the following try-with-resources block: 考虑以下try-with-resources块:

try (Foo foo = getAFoo()) {

}

For some class Foo that implements java.lang.AutoCloseable . 对于实现java.lang.AutoCloseable一些类Foo

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 )? 如果getAFoo()返回null ,那么是否会在结束括号上抛出空指针异常(由于运行时试图调用close )?

According to this Oracle blog : 根据这个Oracle博客

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. 经过充分考虑后,JSR 334专家组已决定对null资源上的try-with-resources语句的语义应更改如下:编译器生成的关闭资源的调用仅在资源为非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). 这意味着,你可以关闭任何null的资源try (使用资源)块而不发出一个错误(和相同的程序时会自动尝试当关闭资源try结束)。

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 . 您实现java.lang.AutoCloseable ,因此编译器将在完成时尝试关闭资源,但只有在资源non-null才会发生关闭资源的进程。 So in this case I think no exception will be thrown. 所以在这种情况下,我认为不会抛出异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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