Proper connection close check not working sonar

In the below code, there is a issue, con,ps,rs close will not be called if an exception is thrown.

public List<String> getRecordData(String email) {
        List<String> data = new ArrayList<>();
        Connection con = getConnection();
        try {
            PreparedStatement ps = con.prepareStatement("select subject from email_record where email=?");
            ps.setString(1, email);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                data.add(rs.getString("subject"));
            }
            rs.close();
            ps.close();
            con.close();
        } catch (SQLException e) {
            throw new TestException(e);
        }
        return data;
    }

But sonarqube or sonarlint does not find any issue in this code. Do I need to enable some additional rules or something here?

sample sonarqube project link - https://sonarcloud.io/project/issues?resolved=false&id=zchandikaz_sonar-test-code

Hello @zchandikaz, welcome to the Sonar Community, and thanks for reporting this issue.

You are right, the code example you shared should close the open resources within a finally block in order to have a correct behavior.

I noticed that such a rule is specified in S3074, but not implemented yet. I’ve created an implementation ticket for it, you can check the progress at [SONARJAVA-4689] - Jira.

Cheers

1 Like

Thanks for the update Angelo

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