I am looking at examples of try-with-resources in Java and I understand the following one:
try (Connection conn = DriverManager.getConnection(url, user, pwd);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);) {
...
}
So, the order of closing is:
rs.close();
stmt.close();
conn.close();
which is perfect because a connection has a statement and a statement has a result set.
However, in the following examples, the order of close I think it is the reverse of the expected:
Example 1:
try (FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr)) {
...
}
The order of closing is:
br.close();
fr.close();
Example 2:
try (FileOutputStream fos = new FileOutputStream("testSer.ser");
ObjectOutputStream oos = new ObjectOutputStream(fs);) {
...
}
The order of closing is:
oos.close();
fos.close();
Are these examples correct? I think the close in those examples should be different because:
The order of closing is: oos. close(); fos. close();
In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.
The Java try with resources construct, AKA Java try-with-resources, is an exception handling mechanism that can automatically close resources like a Java InputStream or a JDBC Connection when you are done with them.
The try -with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try -with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.
The ordering is the same: it's always the reverse of the order in which resources are specified. From JLS:
Resources are closed in the reverse order from that in which they were initialized.
However, if the later-specified resources themselves invoke the close()
method of the earlier-specified resources (as is the case with BufferedReader
and ObjectOutputStream
), it may look like they are not happening in the expected order (and that close()
will be invoked multiple times).
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