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

"NullPointerException" should not be caught

    XMLWordPrintable

    Details

    • Message:
      Make the dereference of XXX conditional on its not being null
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Targeted languages:
      Python, VB.Net
    • Covered Languages:
      C#, Java
    • Irrelevant for Languages:
      ABAP, C, C++, Cobol, HTML, PL/I, PL/SQL, RPG, XML
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      5min
    • Analysis Scope:
      Main Sources
    • CERT:
      ERR08-J.
    • CWE:
      CWE-395
    • PMD:
      AvoidCatchingNPE

      Description

      NullPointerException should be avoided, not caught. Any situation in which NullPointerException is explicitly caught can easily be converted to a null test, and any behavior being carried out in the catch block can easily be moved to the "is null" branch of the conditional.

      Noncompliant Code Example

      public int lengthPlus(String str) {
        int len = 2;
        try {
          len += str.length();
        }
        catch (NullPointerException e) {
          log.info("argument was null");
        }
        return len;
      }
      

      Compliant Solution

      public int lengthPlus(String str) {
        int len = 2;
      
        if (str != null) {
          len += str.length();
        }
        else {
          log.info("argument was null");
        }
        return len;
      }
      

      See

      • MITRE, CWE-395 - Use of NullPointerException Catch to Detect NULL Pointer Dereference
      • CERT, ERR08-J. - Do not catch NullPointerException or any of its ancestors

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              ann.campbell.2 Ann Campbell
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

                Dates

                Created:
                Updated: