For example, I have method for working with input/output streams:
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();
}
}
Method can throws IOException and it is valid behavior. But If I have Exception in this line:
out1.close();
others three Stream will be NOT closed. What solution can you recommend? How? How close all?
I have just one:
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();}
}}
}
}
As you can see - my approach is using multiple try-finally blocks.
Do you think it is good idea?
If three streams are not dependent on each other, may be having try/catch for each stream look cleaner.
Something like:
try{
out1.close();
}catch(Exception e)
{
....
}finally
{.... }
try{
out2.close();
}catch(Exception e)
{
.....
}finally
{.... }
EDIT: As iccthedral suggested, if you use Java7 you may use try-with-resource block.
Probably the best way to go about it is:
try (
OutputStream out1 = ...;
OutputStream out2 = ...;
InputStream in1 = ...;
InputStream in2 = ...;
) {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With