Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-1193

Exception types should not be tested using "instanceof" in catch blocks

    XMLWordPrintable

    Details

    • Message:
      Replace the usage of the "instanceof" operator by a catch block.
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Default Quality Profiles:
      Sonar way
    • Covered Languages:
      Java
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      10min
    • Analysis Scope:
      Main Sources, Test Sources
    • CERT:
      ERR51-J.
    • PMD:
      AvoidInstanceofChecksInCatchClause

      Description

      Multiple catch blocks of the appropriate type should be used instead of catching a general exception, and then testing on the type.

      Noncompliant Code Example

      try {
        /* ... */
      } catch (Exception e) {
        if(e instanceof IOException) { /* ... */ }         // Noncompliant
        if(e instanceof NullPointerException{ /* ... */ }  // Noncompliant
      }
      

      Compliant Solution

      try {
        /* ... */
      } catch (IOException e) { /* ... */ }                // Compliant
      } catch (NullPointerException e) { /* ... */ }       // Compliant
      

      See

      • CERT, ERR51-J. - Prefer user-defined exceptions over more general exception types

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              freddy.mallet Freddy Mallet (Inactive)
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

                Dates

                Created:
                Updated: