【发布时间】:2013-07-13 02:59:15
【问题描述】:
如果抛出异常,我希望缓冲读取器和文件读取器关闭并释放资源。
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;
}
【问题讨论】:
-
再次阅读您的问题后,我不确定我是否理解它。你能解释一下吗?
-
嗨。 Cheetah,我正在尝试了解 Java 6 示例中第一个
catch的作用。即catch (Exception ex) { throw ex; }— 它只是重新抛出异常,它什么都不做,它可以很容易地删除而不会造成任何伤害。还是我错过了什么?