In the new Try-with-Resources syntax in Java 7 do I need to worry about the order of the resources?
try (InputStream in = loadInput(...); // <--- can these be in any order?
OutputStream out = createOutput(...) ){
copy(in, out);
}
catch (Exception e) {
// Problem reading and writing streams.
// Or problem opening one of them.
// If compound error closing streams occurs, it will be recorded on this exception
// as a "suppressedException".
}
Order matters if and only if it would matter when using the normal try {create resources} finally {close resources} syntax. Resources which were acquired first will be closed last. See the technotes for details.
In your example, the order definitely doesn't matter. You only use resources in the try block, where both are already available. If you would be connecting to the database, order or opening matters, but I would create a separate method to cover that. This method needs to implement AutoClosable and override the method close(). Although close() throws an Exception, your method doesn't have to.
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