Do Not Catch NullPointerException

ID

java.no_catch_npe

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

CWE:395, reliability

Description

Reports catch blocks that catch NullPointerException.

Rationale

NullPointerException is a programming error that indicates a null dereference. Catching it masks the root cause instead of fixing it. The correct approach is to add null checks or use Optional before the point where the NPE would occur.

// Bad — masks the null dereference bug
try {
    result = obj.getValue().length();
} catch (NullPointerException e) {
    result = 0;
}

Remediation

Add explicit null checks rather than relying on exception flow control:

// Good — null check before use
if (obj != null && obj.getValue() != null) {
    result = obj.getValue().length();
} else {
    result = 0;
}