In our code we usually use the following pattern:
Connection conn;
try{
conn = getConnection();
//Do databasey stuff
}catch(Exceptions that get thrown){
}finally{
try{
conn.close();
}catch(SQLException ex){
logger.error("Failed to cleanup database connection",ex);
}
}
However findbugs doesn’t like this. Since conn.close() can throw an exception then the connection isn’t guaranteed to be closed.
Is findbugs being too pedantic or is there a better way to close database connections.
Edit:
Added removed try catch around close.
What you really want to be doing is to combine “The Elite Gentleman”‘s answer with the
@edu.umd.cs.findbugs.annotations.SuppressWarnings( "OBL_UNSATISFIED_OBLIGATION" )annotation. FindBugs seems to only be happy if you the complete closing in method in the following manner (which is btw the preferred sequence for doing so):Which is very verbose and you probably don’t want to do if for no other reason than the love of your carpal tunnel, thus you should use the
DBUtils.closeQuietly()method (or create your own, your call). However, FindBugs doesn’t recognise this (i.e. using the library or your own method) as properly closing the resources and issues you a warning. In this case it is clearly a false positive. Therefore must make sure its the only warning you are getting and then disable that specific warning for that method.This way you clean up your resources with the few lines of code and avoid a FindBugs warning.