Will try-with-resources close all opened resources if exception happens?
private void insertUserInAccessTable(int user_id) throws SQLException {
final String sql = "bla bla";
try( Connection con = ...; PreparedStatement ps = ... ) {
...
if(i==0) throw new SQLException();
}
}
It will be closed even if it will throw an exception.
it will be closed regardless of whether the try statement completes normally or abruptly
Reference: http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Yes, but not ones that were initialized outside of the try block or inside its body (after the resource declarations).
// This connection is initialized beforehand and will not be
// closed automatically by try-with-resources
Connection conn = // ...
// The statement WILL always be closed, exception or not, before exiting the try block
try (Statement stmt = conn.createStatement())
{
// This result set will NOT be closed (directly) by try-with-resources
ResultSet rs = stmt.executeQuery(/*...*/);
}
* When try-with-resources closes the Statement, JDBC says the statement should close the ResultSet it created. So it may get closed, but only because of the JDBC contract and not because of try-with-resources.
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