【发布时间】:2011-03-19 08:06:13
【问题描述】:
通常在处理Java IO代码的时候,这里是我写的
FileOutputStream out = null;
try
{
out = new FileOutputStream("myfile.txt");
// More and more code goes here...
}
catch (Exception e)
{
}
finally
{
// I put the close code in finally block, to enture the opened
// file stream is always closed even there is exception happened.
if (out != null) {
// Another try catch block, troublesome.
try {
out.close();
} catch (IOException ex) {
}
}
}
如您所见,当我尝试关闭文件流时,我需要处理另一个 try...catch 块。
看起来很麻烦:(
有什么办法可以避免吗?将关闭代码放在非finally块中我觉得不舒服,因为其他代码引起的异常不会让“关闭”被调用。
【问题讨论】:
-
有人同意你的观点:mail.openjdk.java.net/pipermail/coin-dev/2009-February/… -- JDK7 中的 ARM 块。 --JA
标签: java