By bloid
via java.dzone.com
Published: Feb 01 2008 / 00:32
It's been a while since I wrote some raw JDBC code. I didn't remember that it was so tedious to manually close a series of PreparedStatement objects and make sure that any exception was properly handled and reported.



Comments
dzonelurker replied ago:
Wrong!! Java exception handling code is usually broken in Java books and in Java related blogs. He needs nested try/finally blocks.
jtheory replied ago:
lurker, can you show an example?
I'm thinking:
a) 2 or 3 levels of nested try/finally blocks makes the code significantly harder to read & maintain (and more likely that some developers on the team will screw up the structure, or not bother)
b) he's trying to preserve the *cause* exception properly -- if your statement execution fails and you thus have no ResultSet, the NPE from attempting to close the ResultSet will override the original exception... so yes, everything will be cleaned up, but the exception and stack trace that bubble up (the NPE) will be useless, and the valuable original won't even be logged.
Personally I use safeClose(ResultSet|Statement|Connection) methods, which check for null and log any Exception thrown then return cleanly; then I call those in the finally block (there's no catch block). Technically, it's probably preferable to chain the exceptions, but I've never seen a situation where there was an important problem showing up *only* in errors while closing PreparedStatements or Connections... at least if that does happen, it'll show up in a log audit.
dzonelurker replied ago:
"Personally I use safeClose(ResultSet|Statement|Connection) methods, which check for null and log any Exception thrown then return cleanly; then I call those in the finally block (there's no catch block)."
I do the same in principle. You can give a hint to safeClose() whether the try block has thrown an exception or not, e.g,.
boolean ok = false;
Statement stmt;
ResultSet rs;
try {
..stmt = conn.createStatement();
..rs = stmt.executeQuery( "SELECT * FROM MyTable" );
..while ( rs.next() ) {
....// ...
..}
..ok = true; // last statement in try block
} finally {
....DbUtils.safeClose(ok, stmt, rs);
}
jtheory replied ago:
(oops, double-clicked on the post button... is there no way to delete a comment?)
dzonelurker replied ago:
[redacted]
Voters For This Link (5)
Voters Against This Link (2)