Try using resources in Java 7?

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".
} 
+5
source share
4 answers

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 .

+7
source

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, - .

0

, . , B , A , , A . , , . , A, B, , try-with-resources , B , A.

0

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.

0
source

All Articles