Uploaded image for project: 'SonarJava'
  1. SonarJava
  2. SONARJAVA-443

False positives on S00112 on "throws Exception" when the method is overriden

    XMLWordPrintable

    Details

    • Type: Improvement
    • Status: Closed
    • Priority: Major
    • Resolution: Fixed
    • Affects Version/s: 2.0
    • Fix Version/s: 2.1
    • Component/s: Rules
    • Labels:
      None

      Description

      Let's take the following example:

      class Base {
        public void myMethod() throws Exception {
          /* ... */
        }
      }
      
      class Derived extends Base {
        @Override
        public void myMethod() throws Exception {
          /* ... */
        }
      }
      

      Clearly, Base.myMethod() is noncompliant and should not throw Exception.

      However, when the class Derived is written, IDEs will auto-generate the overriden method including the throws Exception part.

      Now, indeed, developers can remove it, if the method does not actually throw Exception:

      class Derived extends Base {
        @Override
        public void myMethod() {
          /* ... */
        }
      }
      

      This compiles because Java allows to relax throws clauses in derived classes (but not to strengthen them).

      However, that is not a well known Java feature, and most developers therefore do not use it.

      Moreover, in the common case where the super method is called, it won't work, as in:

      class Derived extends Base {
        @Override
        public void myMethod() throws Exception {
          super.myMethod(); // This throws Exception, so the "throws Exception" must be in the signature, or the exception must be handled
        }
      }
      

      Therefore, it is best to simply not report those issues on methods which have the @Override annotation.

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              benzonico OLD - Nicolas Peru
              Reporter:
              dinesh.bolkensteyn Dinesh Bolkensteyn (Inactive)
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

                Dates

                Due:
                Created:
                Updated:
                Resolved: