例如,我有处理输入/输出流的方法:
public void doSomethingWithStreams () throws FileNotFoundException, IOException
{
OutputStream out1, out2;
InputStream in1, in2;
try{
//do something with Streams: read, write, process, etc.
}
finally{
//There I try to close connections
out1.close();
out2.close();
in1.close();
in2.close();
}
}
方法可以抛出IOException并且它是有效的行为。 但如果我在这一行中有例外:
out1.close();
其他三个Stream将 NOT 关闭。 你能推荐什么解决方案?怎么样?有多接近所有?
我只有一个:
public void doSomethingWithStreams () throws FileNotFoundException, IOException
{
OutputStream out1, out2;
InputStream in1, in2;
try{
//do something with Streams: read, write, process, etc.
}
finally{
//There I try to close connections
try{out1.close();}
finally{
try{out2.close();}
finally{
try{in1.close();}
finally{
in2.close();}
}}
}
}
正如您所看到的 - 我的方法是使用多个try-finally块。
你认为这是个好主意吗?
答案 0 :(得分:6)
如果三个流不相互依赖,可能会尝试/捕获每个流看起来更清洁。
类似的东西:
try{
out1.close();
}catch(Exception e)
{
....
}finally
{.... }
try{
out2.close();
}catch(Exception e)
{
.....
}finally
{.... }
编辑:正如iccthedral建议的那样,如果您使用Java7,则可以使用try-with-resource阻止。
答案 1 :(得分:2)
可能最好的方法是:
try (
OutputStream out1 = ...;
OutputStream out2 = ...;
InputStream in1 = ...;
InputStream in2 = ...;
) {
...
}
答案 2 :(得分:2)
清理它的最佳方法可能就是制作一个这样的方法:
public static void close(Closeable c) {
if (c == null) return;
try {
c.close();
} catch (IOException e) {
// Do anything or nothing
}
}
这可以替换你的.close()调用,如果失败则不会抛出异常。