Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
    }
}
like image 874
andy007 Avatar asked Nov 21 '25 23:11

andy007


2 Answers

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

like image 190
Adil Aliyev Avatar answered Nov 23 '25 13:11

Adil Aliyev


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.

like image 20
William Price Avatar answered Nov 23 '25 14:11

William Price



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!