2

null在调用close()开放资源之前,网上有一些例子。

final InputStream in = ...; // may throw IOException
try {
    // do something.
} finally {
    if (in != null) { // this is really required?
        in.close();
    }
}

我一直没有null-checking-if.

final InputStream in = ...; // may throw IOException
try {                  // when it reached to this line 'in' is never null, could it be?
    // do something.
} finally {
    in.close(); // no null check required, am i wrong?
}
4

3 回答 3

2

如果资源没有机会进入null任何代码执行路径,则对空值检查的需求为零。

你在做正确的事。

于 2013-05-06T01:28:52.643 回答
1
final InputStream in = ...;

...可能会返回,这null就是为什么会有支票。

于 2013-05-06T01:27:39.613 回答
1

InputStream 实现了 AutoClosable,因此您可以使用try-with-resources语句。然后,您不必像 Java 为您那样处理 null。

try (InputStream in = ...) {
    [some code]
} 
于 2018-01-26T10:47:50.743 回答