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.
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.
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.
The following code mistakenly catches a NullPointerException.
This category identifies Software Fault Patterns (SFPs) within the Unchecked Status Condition cluster (SFP4).
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/...
This category represents one of the phyla in the Seven Pernicious Kingdoms vulnerability classification. It includes weaknesses that occur when an application does not...
This view (slice) covers all the elements in CWE.
CWE identifiers in this view are weaknesses that do not have associated Software Fault Patterns (SFPs), as covered by the CWE-888 view. As such, they represent gaps in...
This view (slice) lists weaknesses that can be introduced during implementation.