Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sonarqube false positive for "Use try-with-resources or close this "ResultSet" in a "finally" clause"

Sonarqube keeps marking code with this issue which is, in my opinion, a false positive. Code looks like this:

try(PreparedStatement st=con.prepareStatement(myQuery)){
    st.setInt(1, myValue);
    ...
    ResultSet rs = st.executeQuery();
    ...
}

If I'm not mistaken, the PreparedStatement implements Closeable and, when closing itself, it also closes the underlying ResultSet.

This behaviour would prevent the ResultSet from being kept open, yet Sonarqube analysis marks it as a critical error.

Am I mistaken? Any way of making Sonarqube ignore this rule under this circumstances?

Tested under Sonarqube 6.7.3 and JDK 8.

From the ResultSet javadoc:

A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results.

like image 620
Pablo Fradua Avatar asked Dec 07 '25 04:12

Pablo Fradua


2 Answers

Indeed this is a false positive. It was already reported and there is open ticket to fix it https://jira.sonarsource.com/browse/SONARJAVA-2060

You can mark the issue as false positive in SonarQube UI, or add // NOSONAR comment on the line where the issue is raised to ignore it.

like image 90
Tibor Blenessy Avatar answered Dec 08 '25 19:12

Tibor Blenessy


It's probably unreasonable to expect code analyzers to know such things. Can a tool know all the -additional- semantics of all Closeables in all libraries written anywhere anytime ?

The doco indeed mentions that "the current ResultSet, if any, is also closed".

Note "the current". What happens if you happen to have two distinct executeQuery() invocations ? Will it fail on bad status or some such ? Will there be two distinct ResultSet objects, both unclosed and one of them now unreferenced ?

(Note : two distinct executeQuery() invocations might sound like completely insane, but remember "coders can do anything" and that is even the very reason why tools such as SonarQube are written in the first place.)

I'm not saying it's entirely undebatable, but to me it doesn't seem that strange if the analysis tool just sees you getting a Closeable and not closing it and just simply complain about it.

like image 30
Erwin Smout Avatar answered Dec 08 '25 18:12

Erwin Smout



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!