Use of NullPointerException Catch to Detect NULL Pointer Dereference

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


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.

Demonstrations

The following examples help to illustrate the nature of this weakness and describe methods or techniques which can be used to mitigate the risk.

Note that the examples here are by no means exhaustive and any given weakness may have many subtle varieties, each of which may require different detection methods or runtime controls.

Example One

The following code mistakenly catches a NullPointerException.

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

See Also

Comprehensive Categorization: Insufficient Control Flow Management

Weaknesses in this category are related to insufficient control flow management.

SFP Secondary Cluster: Unchecked Status Condition

This category identifies Software Fault Patterns (SFPs) within the Unchecked Status Condition cluster (SFP4).

Error Conditions, Return Values, Status Codes

This category includes weaknesses that occur if a function does not generate the correct return/status code, or if the application does not handle all possible return/...

Comprehensive CWE Dictionary

This view (slice) covers all the elements in CWE.

Weaknesses Introduced During Implementation

This view (slice) lists weaknesses that can be introduced during implementation.

Weakness Base Elements

This view (slice) displays only weakness base elements.


Common Weakness Enumeration content on this website is copyright of The MITRE Corporation unless otherwise specified. Use of the Common Weakness Enumeration and the associated references on this website are subject to the Terms of Use as specified by The MITRE Corporation.