3

只是一个简单的问题。鉴于此代码:

try {
    // operation on inputstream "is"
} finally {
    try {
        is.close();
    } catch (IOException ioe) {
        //if ioe is thrown, will the handle opened by 'is' be closed?
    }
}

如果close()抛出,文件句柄是否仍然存在(并泄漏),还是已经关闭?

4

1 回答 1

3

不可靠。如果is.close()抛出,is可能不会标记为关闭。无论如何,您对此无能为力。你不知道它的内部结构is。Java 7 等价物只是隐藏了这个问题。

try (InputStream is = Files.newInputStream(...)) {
    // Stuff with is.
} catch (IOException is) {
    ...  // Handles exceptions from the try block.
}  // No finally. Handled by try-with-reources

如果自动关闭抛出,该异常是一个抑制异常,你永远不会知道文件句柄是否或何时被回收。

于 2013-10-08T22:41:07.390 回答