In our code base we get Sonar reports violation for rule squid:S2095 on code like the following:
PreparedStatement ps = null;
try {
ps = connection.prepareStatement(DML);
ps.setString(1, externalDeviceId);
ps.setInt(2, internalDeviceId);
ps.execute();
return ps.getUpdateCount() > 0;
} finally {
Utilities.close(ps);
}
with Utilities.close implemented as
public static final void close(final AutoCloseable ac) {
if(ac != null) {
try {
ac.close();
} catch(Exception e) {
}
}
}
Is there a way to avoid these false positives?
How do I get rid of issues that are False-Positives? You can mark individual issues False Positive or Won't Fix through the issues interface. If you're using PR analysis provided by the Developer Edition, issues marked False Positive or Won't Fix will retain that status after merge.
If you use Java 7+, there is a much simple way to use try-with-resources that is able to close resource itself and you needn't take care about that anymore. See try (PreparedStatement ps = connection.prepareStatement(DML)), a tutorial: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
try (PreparedStatement ps = connection.prepareStatement(DML)) {
ps.setString(1, externalDeviceId);
ps.setInt(2, internalDeviceId);
ps.execute();
return ps.getUpdateCount() > 0;
}
Short answer, there is no way to avoid those for the moment.
Longer answer : Normally, passing an opened value to a method should mark it as closed to avoid false positive. You should precise the sonar java plugin version you are using.
This rule is relying on symbolic execution engine and is limited to the boundaries of a method and as such, there is no way to determine for the moment that a call to this utility method will for sure close the open resource.
Note however that the sonar java team is working to make this limit go away.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With