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

"NullPointerException" should not be explicitly thrown

    XMLWordPrintable

    Details

    • Message:
      Throw some other exception here, such as "IllegalArgumentException".
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Targeted languages:
      C#, Python, VB.Net
    • Covered Languages:
      Java
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      10min
    • Analysis Scope:
      Main Sources
    • PMD:
      AvoidThrowingNullPointerException

      Description

      A NullPointerException should indicate that a null value was unexpectedly encountered. Good programming practice dictates that code is structured to avoid NPE's.

      Explicitly throwing NullPointerException forces a method's callers to explicitly catch it, rather than coding to avoid it. Further, it makes it difficult to distinguish between the unexpectedly-encountered null value and the condition which causes the method to purposely throw an NPE.

      If an NPE is being thrown to indicate that a parameter to the method should not have been null, use the @NotNull annotation instead.

      Noncompliant Code Example

      public void doSomething (String aString) throws NullPointerException {
           throw new NullPointerException();
      }
      

      Compliant Solution

      public void doSomething (@NotNull String aString) {
      }
      

        Attachments

          Issue Links

            Activity

              People

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

                Dates

                Created:
                Updated: