0

I'd like to find a way to hint SonarQube so that it would not warn for some pieces of code.

Example1: "empty statement block can be removed" -- actually, it cannot be removed:

static void closeNX (java.io.FileInputStream is) {
    try {
        is.close ();
    } catch (Exception e) {} <Warning comes here>
}

(Edit: this method is called when is.read or is.write has already thrown an Exception, so any more Exception from is.close is not needed.)

Example2: finalize is deprecated, as the memory will be eventually released even if the user of your library forget to call close/dispose -- but native resources (opened files, sockets, IPC, whatever) won't be released, that's why for example java.io.FileInputStream does have finalize method:

protected void finalize() throws IOException {
    if ((fd != null) &&  (fd != FileDescriptor.in)) {
        close();
    }
}

(Edit: even having finalize doesn't warrant that native resources will be released if the user doesn't call close/dispose; but non-having finalize does warrant that native resources won't be released if the user doesn't call close/dispose)

Lorinczy Zsigmond
  • 1,749
  • 1
  • 14
  • 21

1 Answers1

1

To silence the message you can either configure which rules are enabled in SonarQube by configuring your quality profile, or you can add an exclusion for particular file.

The third way is to add // NOSONAR comment on the line with the issue. However, this way you are muting all rules.

Now about the examples, you provided - empty catch block can't be removed, however, it's considered to be a code smell. Perhaps an exception should be at least logged? See here for more discussion Why are empty catch blocks a bad idea?

For finalize, it's not a good idea to use them to release resources because there is no guarantee when finalize will be invoked or if it will be invoked at all. It's better to release resources explicitly rather than rely on garbage collection to invoke finalize. You can check these bugs in JDK why even Java authors prefer not to use finalize in java.io.FileInputStream https://bugs.openjdk.java.net/browse/JDK-8187325 , https://bugs.openjdk.java.net/browse/JDK-8212050

Tibor Blenessy
  • 4,254
  • 29
  • 35