SonarQube giving false positive for PreparedStatement / ResultSet etc

  • versions Community Edition - Version 8.1 (build 31237)
 try {
            StringBuffer sqlStmt = new StringBuffer();
            sqlStmt.append("SELECT ...");
            pst = cn.prepareStatement(sqlStmt.toString());
            pst.setString(1, uniqueNumber);
            rs = pst.executeQuery();
            if (rs.next()) {
                return rs.getString("VENDOR_NUMBER");
            }
            return null;
        } catch (Exception e) {
            throw e;
        } finally {
            if (rs != null) {
                rs.close();
            }
            if (pst != null) {
                pst.close();
            }
        }

Image of the SonarQube output
https://pasteboard.co/JD3kaVh.png

Hey there.

What version of the Java analyzer is installed on your SonarQube instance?

How can I check that?

The Global Administration > Marketplace, or the /extensions/plugins/ directory of your SonarQube installation.

SonarJava
5.14 (build 18788)

Hey there. Thanks for the update.

The latest version of our Java analyzer compatible with SonarQube v8.1 is v6.3.2.
v6.0 was a full re-write of our Java analyser – such a huge rewrite, we don’t actually have a full list of the many false-positives addressed.

You should try and reproduce the issue using this version of our Java analyzer (upgrading the plugin), or better yet upgrade to SonarQube v8.5. When using a non-LTS version of SonarQube, it’s best to make sure you’re continuing to upgrade as there are new releases.

Hi,
I updated the plugin to 6.3.2 and rescanned the entire project again but still facing the same false positive again. The prepared statements are closed in finally block but still it is giving issue “Use try-with-resources or close this “PreparedStatement” in a “finally” clause.”.

Still it reports same false positive after update.
Image Link of SonarQube output - https://pasteboard.co/JDa0EeU.png

Hello @bb_evo,

The issue here is that close() can throw an exception (see signature in javadoc), when this happens, the other close will not be called, ending up with an unclosed resource. If you modify the code to handle the exception, something like:

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

(or any variation suiting your needs), no issue is raised anymore.
It is correct but quite cumbersome, this is why we also suggest having a look at try-with-resources, to see if it could not simplify your code.

Hope it clarifies the situation.

2 Likes