andy007
andy007

Reputation: 917

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

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

Upvotes: 3

Views: 1147

Answers (2)

William Price
William Price

Reputation: 4102

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.

Upvotes: 3

Adil Aliyev
Adil Aliyev

Reputation: 1169

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

Upvotes: 4

Related Questions