CWE-395: Use of NullPointerException Catch to Detect NULL Pointer Dereference
Use of NullPointerException Catch to Detect NULL Pointer Dereference
Weakness ID: 395 (Weakness Base)
Status: Draft
Description
Description Summary
Catching NullPointerException should not be used as an
alternative to programmatic checks to prevent dereferencing a null
pointer.
Time of Introduction
Implementation
Applicable Platforms
Languages
Java
Demonstrative Examples
Example 1
The following code mistakenly catches a
NullPointerException.
(Bad Code)
Java
try {
mysteryMethod();
} catch (NullPointerException npe) {
}
Potential Mitigations
Phase
Description
Do not extensively rely on catching exceptions (especially for
validating user input) to handle errors. Handling exceptions can
decrease the performance of an application.
Other Notes
Programmers typically catch NullPointerException under three
circumstances: 1. The program contains a null pointer dereference. Catching
the resulting exception was easier than fixing the underlying problem. 2.
The program explicitly throws a NullPointerException to signal an error
condition. 3. 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.