Will try-with-resources close resources if exception happens?

1k Views Asked by At

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();
    }
}
2

There are 2 best solutions below

2
On BEST ANSWER

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.

0
On

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