Do Not Throw NullPointerException
ID |
java.no_throw_npe |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
CWE:248, reliability |
Rationale
Explicitly throwing NullPointerException is almost always a code smell. In stack traces it is indistinguishable from a genuine null-dereference bug, making diagnosis harder. Callers who see NullPointerException cannot tell whether the failure is an argument-validation guard or an accidental null access.
// Bad -- looks like a real NPE bug in stack traces
public void process(String input) {
if (input == null) {
throw new NullPointerException("input is null");
}
}
Remediation
Use IllegalArgumentException for argument validation or Objects.requireNonNull() for null-guard preconditions:
// Good -- clear semantics
public void process(String input) {
if (input == null) {
throw new IllegalArgumentException("input must not be null");
}
}
// Good -- concise precondition
public void process(String input) {
Objects.requireNonNull(input, "input must not be null");
}