So in some method, I will be opening a new IO stream, doing some processing with it, and then using that stream as the input to open up another IO stream. I don't believe I can use a single try-with-resources block because of the processing with the first IO stream being in between opening the first and second streams. So with that said, would it be better (in a coding-design sense) to use a single try-catch-finally block to open and close these streams or use nested try-with-resources blocks to open and close the streams? I know that if there is no processing between the first and second IO streams, it would be best to open all three streams in a single try-with-resources block.
A simplistic example follows:
Try-Catch-Finally
void someMethod(InputStream is) throws SomeException {
SomeIOStream io1 = null;
SomeIOStream io2 = null;
SomeIOStream io3 = null;
try{
io1 = new SomeIOStream( someSortOfProcessing() );
io1.moreStreamProcessing();
io2 = new SomeIOStream( someSortOfProcessing(io1) );
io3 = new SomeIOStream (is);
//do stuff with io2 and io3
} catch (Throwable t) {
//Exception Handling
} finally {
//closing streams io3, io2, io1, is
}
}
Try-with-resources
void someMethod(InputStream is) throws SomeException {
try ( SomeIOStream io1 = new SomeIOStream( someSortOfProcessing() ) ){
io1.moreStreamProcessing();
try ( SomeIOStream io2 = new SomeIOStream( someSortOfProcessing(io1) );
SomeIOStreeam io3 = new SomeIOStream (is); ){
//do stuff with io2 and io3
}
} catch (Throwable t) {
//Exception Handling
} finally {
//closing stream is
}
}
To me, it looks as though the first is cleaner, but the second has the benefits of a try-with-resources block. Of course, another alternative is to open the initial io1 with try-with-resources, but open io2 and io3 within that try-block. So would this third mixed approach be better than the above two?
Mixed Approach
void someMethod(InputStream is) throws SomeException {
SomeIOStream io1 = null;
SomeIOStream io2 = null;
SomeIOStream io3 = null;
try (SomeIOStream io1 = new SomeIOStream( someSortOfProcessing() ) ){
io1.moreStreamProcessing();
io2 = new SomeIOStream( someSortOfProcessing(io1) );
io3 = new SomeIOStream (is);
//do stuff with io2 and io3
} catch (Throwable t) {
//Exception Handling
} finally {
//closing streams io3, io2, is
}
}
Also as an additional question, am I right to assume that the only way to close the InputStream is
would be to put it in the finally-block?