In the new Try-with-Resources syntax in Java 7, do I need to worry about the order of 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 matters when using the usual {create resources} syntax. Resources that were acquired first will be closed last. See techno for more details .
Actually, the order doesn't matter. Ideally, if the resources are not connected to each other, you can open them in any order, and they can be closed in any order.
, , Connection, PreparedStatement, , , java FIFO, - .
, . , B , A , , A . , , . , A, B, , try-with-resources , B , A.
In your example, the order definitely doesn't matter. You only use resources in the try block, where both are already available. If you connect to the database, order or open-ended questions, but I would create a separate method to cover this. This method should implement AutoClosable and override the close () method. Although close () throws an exception, your method is not required.