"Resources should be closed" (squid:S2095) false-positive

Hello,

I found an example in the SonarCloud that looks like “squid:S2095” can’t identify the second resource being closed, leading to a false-positive. Also confirmed in SonarLint for Eclipse 4.1.

I made a gist with minimal steps for reproduction. The gist contains two almost identical methods, they only differ by the order in which the resources are closed in the finally block.

It is possible to note that within makeDisplayCopy() the violation is at line 19 (referring to out), which is the second resource closed in the finally block. While in makeDisplayCopy2() the violation is at line 50 (referring to in), which is the second resource closed in the finally block.

Is this indeed a false-positive? Thanks!

Hi!

I don’t think it’s a false positive. The FileReader class extends InputStreamReader and the FileWriter class extends OutputStreamWriter

Looking at the javadocs, you can see that the close() method can throw an exception:

Throws:
IOException - If an I/O error occurs

Therefore, in your examples if the first .close() throws an exception, the second .close() won’t be called, leaving the resource opened.

1 Like