Why is SonarQube plugin for Jenkins complaining about the open statement if I close it in the finally block?
(I need to validate database connections in a separate function.)
final String PING = "SELECT 1 from dual";
public boolean validateConnection(Connection conn) {
PreparedStatement statement = null;
try{
if(conn == null){
LOGGER.log( LogEntries.PingError, "Null connection on PING. Reached max # of connections or network issue. Stats: "+getCacheStatistics() );
return false;
}
if(conn.isClosed()){
// logger
return false;
}
statement = conn.prepareStatement( PING ); //%%%%%% SONAR: Close this "PreparedStatement".
statement.setQueryTimeout(QUERY_TIMEOUT);
try( ResultSet rs = statement.executeQuery() ){
if ( rs != null && rs.next() ) {
return true;
}
}catch(Exception exRs){
// logger
throw exRs;
}
}catch(Exception ex){
// logger
}finally{
try{
statement.close();
}catch(Exception excpt){
// logger
}
}
return false;
}
I've refactored my code in this way as suggested by @TT and sonar stopped complaining.
Without "try-with-resource" the code could be refactored in the following way but in this case Sonar still complains:
I donnot see the point of putting all this nested
try
blocks with nocatch
. You need only the firsttry
with the suitablecatch
andfinally
where you close yourstatment
s andconnection
after checking them againstnull
.