gpt4 book ai didi

java-7 - 我是否正确使用了 Java 7 try-with-resources

转载 作者:行者123 更新时间:2023-12-03 05:05:21 25 4
gpt4 key购买 nike

如果抛出异常,我希望缓冲读取器和文件读取器关闭并释放资源。

public static Object[] fromFile(String filePath) throws FileNotFoundException, IOException
{
try (BufferedReader br = new BufferedReader(new FileReader(filePath)))
{
return read(br);
}
}

但是,是否需要有 catch 子句才能成功关闭?

编辑:

本质上,Java 7 中的上述代码是否等同于 Java 6 中的以下代码:

public static Object[] fromFile(String filePath) throws FileNotFoundException, IOException
{

BufferedReader br = null;

try
{
br = new BufferedReader(new FileReader(filePath));

return read(br);
}
catch (Exception ex)
{
throw ex;
}
finally
{
try
{
if (br != null) br.close();
}
catch(Exception ex)
{
}
}

return null;
}

最佳答案

这是正确的,并且不需要 catch 子句。 Oracle java 7 文档表示,无论是否实际抛出异常,资源都将被关闭。

仅当您想对异常使用react时,才应使用 catch 子句。 catch 子句将在资源关闭后执行。

这是来自 Oracle's tutorial 的片段:

The following example reads the first line from a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program is finished with it:

static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
return br.readLine();
}
} // In this example, the resource declared in the try-with-resources statement is a BufferedReader.

... Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).

编辑

关于新编辑的问题:

Java 6 中的代码执行 catch ,然后执行 finally block 。这会导致资源仍然可能在 catch block 中打开。

在 Java 7 语法中,资源在 catch block 之前关闭,因此在 catch block 执行期间资源已关闭。这记录在上面的链接中:

In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.

关于java-7 - 我是否正确使用了 Java 7 try-with-resources,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17650970/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com