Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ensure objects are closed if an exception is thrown

Tags:

java

I am creating JDBC Statements and ResultSets.

Findbugs rightly points out that I don't close these if an exception is thrown.

So now I have:

Statement stmt = null;
ResultSet res = null;
try {
    stmt = ...
    res = stmt.executeQuery(...);
    ...
} finally {
    try {
        if(res != null)
           res.close(); // <-- can throw SQLException
    } finally {
        if(stmt != null)
           stmt.close();
    }
}

(Only I have rather more result sets and prepared statements and so on open... so my nesting of finallys is rather deeper)

There has to a better way to ensure a large number of result sets are closed?

(Aside: in Symbian they never let destructors/close/release/remove -type methods throw any errors. I think this a very good design decision. That all the close methods in JDBC can throw SQLException makes things unnecessarily complicated, in my opinion.)

like image 322
Will Avatar asked May 13 '13 12:05

Will


1 Answers

If you are using Java 7, then you can take advantage of the fact ResultSet extends AutoCloseable and use a try-with-resources statement.

try (Statement sql = <WHATEVER>;
     ResultsSet res = sql.executeQuery(<WHATEVER>)) {
     // Use results
}

At least then you avoid the finally clauses.

like image 90
Duncan Jones Avatar answered Sep 18 '22 05:09

Duncan Jones