我期望缓冲读取器和文件读取器关闭,并在抛出异常时释放资源。
public static Object[] fromFile(String filePath) throws FileNotFoundException, IOException
{
try (BufferedReader br = new BufferedReader(new FileReader(filePath)))
{
return read(br);
}
}
但是,是否有要求catch
成功关闭的条款?
EDIT:
本质上,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 文档说资源将被关闭不管是否实际抛出异常。
你应该使用catch
仅当您想对异常做出反应时才使用该子句。这catch
条款将被执行after资源已关闭。
这是来自的一个片段Oracle 的教程:
以下示例从文件中读取第一行。它使用一个
BufferedReader 的实例从文件中读取数据。缓冲读取器
是程序结束后必须关闭的资源
它:
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.
...因为 BufferedReader 实例是在
try-with-resource语句,无论是否存在都会关闭
try 语句正常或突然完成(由于
方法 BufferedReader.readLine 抛出 IOException)。
EDIT
关于新编辑的问题:
Java 6 中的代码执行catch
之后的finally
堵塞。这会导致资源仍然可能在catch
block.
在Java 7语法中,资源是关闭的before the catch
块,因此资源在该期间已经关闭catch
块执行。这在上面的链接中有记录:
在 try-with-resources 语句中,运行任何 catch 或 finally 块
声明的资源被关闭后。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)