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.)
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.
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