S2095 - PreparedStatement closure in finally ignored when not first line

  • versions used (SonarQube Community Edition, sonar-java-plugin-
  • error observed: False positive scan as bug for submitted code Rule S2095 - Use try-with-resources or close this “PreparedStatement” in a “finally” clause. The bug is marked on the line where the PreparedStatement is returned from the Connection%prepareStatement call.
  • Scan the submitted code.
  • workaround? It seems to not show as a bug to change the order of the statements in the close.
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;

class SonarScanFalsePositiveS2095 {

    public void openSomething(Connection conn) throws SQLException {
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = conn.prepareStatement("SELECT * FROM addresses;");
            rs = ps.executeQuery();
        } finally {
            if (rs != null) rs.close();
            if (ps != null) ps.close();

Hi @hajush,

The problem in this code is that rs.close() might throw an exception, which would prevent ps from being closed. I recommend using try-with-resources to avoid issues like this. Without try-with-resources closing multiple resources requires nested try-finally statements to prevent exceptions in one close methods from preventing the other close methods from executing.

PS: The issue goes away if you change the order because closing the prepared statement will automatically close the result set as well. So if you change the order, the call to rs.close() actually becomes redundant and SonarQube no longer cares whether it’s actually reached or not.


1 Like

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