Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try-with-resources in Java 7?

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".
} 
like image 725
citizen conn Avatar asked Jul 13 '11 03:07

citizen conn


2 Answers

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.

like image 195
Prodicus Avatar answered Jan 01 '23 13:01

Prodicus


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.

like image 35
Sabina Orazem Avatar answered Jan 01 '23 14:01

Sabina Orazem