CWE-395: Use of NullPointerException Catch to Detect NULL Pointer Dereference

Description

Catching NullPointerException should not be used as an alternative to programmatic checks to prevent dereferencing a null pointer.

Submission Date :

July 19, 2006, midnight

Modification Date :

2023-06-29 00:00:00+00:00

Organization :

MITRE
Extended Description

Programmers typically catch NullPointerException under three circumstances:

  • The program contains a null pointer dereference. Catching the resulting exception was easier than fixing the underlying problem.
  • The program explicitly throws a NullPointerException to signal an error condition.
  • The code is part of a test harness that supplies unexpected input to the classes under test.

    Of these three circumstances, only the last is acceptable.

Example Vulnerable Codes

Example - 1

The following code mistakenly catches a NullPointerException.

mysteryMethod();
try {} catch (NullPointerException npe) {}

Related Weaknesses

This table shows the weaknesses and high level categories that are related to this weakness. These relationships are defined to give an overview of the different insight to similar items that may exist at higher and lower levels of abstraction.

Visit http://cwe.mitre.org/ for more details.