Use try-with-resources or close this "PreparedStatement" in a "finally" clause

sonarqube-8.4.0.35506
sonar-scanner-4.4.0.2170-windows
NetBeans 8.2, jdk1.8.0_241

Hi, according to Sonnarqube, why the next code is a bug?

PreparedStatement  pst = null;
ResulSet rs = null;

try {
     pst= myConnection.prepareStatement (A_SELECT_QUERY);
    rs = pst.executeQuery ();
      while (rs.next()) {
          // Do something....
     } 
}
catch (Exception e) {
       // Do something....
}
finally {
       if (rs!= null){
            rs.close();
        }
       if (pst!=null){
           pst.close()
       }
}

The preparestatement is closed in a finally clause. Where is the problem?
Thanks in advance!
Gabriel

Hi,

Welcome to the community!

According to the javadoc the ResultSet.close method throws SQLException.

If your rs.close() call does that, then pst.close is never reached. So either you do this laborious exercise:

finally {
  try {
    if (rs != null){ 
      rs.close();
    }
  } finally {
    if (pst != null) {
// &etc
    }
  }
}

OR you create your objects with a try-with-resources (as demonstrated in the rule description, which is available from the issue box when you click “Why is this an issue”) and they’re closed automatically for you without all the rigmarole & if-ing.

 
HTH,
Ann

1 Like

Hi Ann
Thank you for your help! I could resolve the error follow your indicationes. I use Java 1.8, so I can’t use “try-with-resources”. Its ok for me use try/catch/finally.

Best regards.
Gabriel

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.