FN in S2221: Catching a Generic Exception not reported as issue

Hi there,

I’m using Sonar Community 7.9.2.30863, sonar-scanner 4.2.0.1873-linux and the Java plugin 6.3 (build 21585).

My profile contains the rule java:S2221 (“Exception” should not be caught when not required by called methods) but I found one method (see below) catching a generic exception and nothing is reported.

    @Override
public void putData(AbstractCortexOperation op) {
    try {
        dataBuffer.put(op);
    } catch (final NullPointerException e) {
        LOGGER.log(Level.WARNING, "Some error text", e);
    } catch (final Exception e) {
        LOGGER.log(Level.WARNING, "Some other error text: ", e);
    }
}

I checked the parent class and it is not throwing Exception, just NullPointerException and InterruptedException. So I see no reason for this case not being caught by the rule.

I could not find any related bug either, so I’m creating this one. Any help will be appreciated.

Regards,
Jose

Hello, welcome to the community!

Indeed, since dataBuffer.put(op); is not throwing explicitly Exception, this is exactly the kind of issue that the rule should detect.
As a test, you could try to change your code to:

@Override
public void putData(AbstractCortexOperation op) {
    try {
        //dataBuffer.put(op);
        foo();
    } catch (final NullPointerException e) {
        LOGGER.log(Level.WARNING, "Some error text", e);
    } catch (final Exception e) {
        LOGGER.log(Level.WARNING, "Some other error text: ", e);
    }
}

void foo() throws NullPointerException,InterruptedException {}

You should see an issue there. (at least, I have it on my side).

  • If you don’t see an issue.

This means that the rule is not executed. I advise you to double-check that everything is correctly configured (see the documentation). Specifically that the profile containing the rule is the default one for Java.

  • If you see an issue.

My guess is that the analyzer cannot resolve the method call dataBuffer.put(op);. In such cases, we are not reporting an issue to avoid false positives. It’s typically due to a project’s properties misconfiguration (probably sonar.java.libraries missing). Checks the logs if you see something strange. I invite you to have a look there, it’s not the same root cause, but I believe the resolution is the same.

I hope this will leads your researches.
Best,
Quentin

1 Like

Hi Quentin,

You are absolutely right and it was a problem with the sonar.java.libraries parameter. Your test worked as you mentioned and now, pointing to the right library folder, I’m getting all the issues about the generic exceptions. Thanks a lot! :smiley:

Best regards!
Jose

1 Like