<分区>
例如,我有处理输入/输出流的方法:
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 block 。
你认为这是个好主意吗?