例如,我有处理输入/输出流的方法:
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 将不会关闭。您可以推荐什么解决方案?如何?到底有多近?
我只有一个:
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 块。
你认为这是个好主意吗?