S1130 FP when overridden method throws checked exception

  • What language is this for? Java
  • Which rule? S1130
  • Why do you believe it’s a false-positive/false-negative? Overriding method wants to throw a checked exception. In order to permit this, parent method has to declare throws as well, regardless of whether parent implementation does throw it or not.
  • Are you using
    • SonarQube Server / Community Build - which version?
    • SonarQube for IDE - which IDE/version?
      • in connected mode with SonarQube Server / Community Build or SonarQube Cloud? Community 24.12.0.100206
  • How can we reproduce the problem? Give us a self-contained snippet of code (formatted text, no screenshots)
class A {
  void foo() throws Exception { // FP
     bar(); // doesn't throw
  }

  void bar() {
    // Some code 
  }
}

class B extends A {
@Override void foo() throws Exception {
    throw new Exception("Here we do throw");
  }

}

You could argue it is a design smell if a sub class throws an exception which the parent doesn’t. However, the suggested fix does not compile.

Hello,

Your class A knows nothing about class B. It does not know that it is going to be extended. Why is it declaring an exception when it has not use for it?

If the intent is to declare a behavior for something that is designed to be extended shouldn’t there be an interface?

With the following code I no longer get an issue from SonarQube :

    interface Aitf {
        void foo() throws Exception;
    }

    class A implements Aitf {
        public void foo() throws Exception {
            bar(); // doesn't throw
        }

        void bar() {
            // Some code
        }
    }

    class B extends A {
        @Override public void foo() throws Exception {
            throw new Exception("Here we do throw");
        }

    }

Without this interface defining the intention all non final methods should throw Exception, which does not seem to be useful.

Not sure this is a FP. Not sure how the analysis can do any better when looking at class A, as it can not possibly know if and how it is going to be extended.

Kind regards.

2 Likes

I think Daniel response completely hits the mark.
When we analyze files and see a single class at the root with some methods declared, we cannot possibly know how those are going to be used/overridden.

Not only we should allow every method to throws Exception , we should actually report methods who do not do that as issues, because they would be restricting the scope of future overriding methods! :sweat_smile:

The point is that extending a class has exactly the scope of allowing child classes to inherit the parent’s behavior (methods with their signatures) and possibly overriding them, not the other way around.

Fair point. Using an interface looks like the right thing to do here. Perhaps this could be added as a hint in the rule documentation.

1 Like