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:
{….
}
{….
}
EDIT: As iccthedral suggested, if you use Java7 you may use try-with-resource block.