In Java, it is tempting to wrap a risky block in catch (NullPointerException e) and move on. CWE-395 says catching NullPointerException should not be used as an alternative to programmatic checks that prevent dereferencing a null pointer.
It is a Java specific weakness in MITRE's record. The practical risk is availability: exceptions are expensive, and an attacker who can force the exception path repeatedly can burn CPU.
How it happens
MITRE lists three reasons programmers catch NullPointerException:
- The program contains a null pointer dereference, and catching the 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, MITRE says, only the last is acceptable.
String domain;
try {
domain = user.getEmail().split("@")[1];
} catch (NullPointerException e) {
domain = "unknown";
}
The code works, but the null is a normal case being handled by an exception. Each bad request pays the cost of creating and unwinding a stack trace.
What an attacker gains
MITRE lists availability: denial of service through CPU resource consumption. Handling exceptions can reduce an application's performance, so a flood of inputs that trigger the exception path makes the service slower for everyone.
How to find it
MITRE notes several techniques that offer partial coverage, citing SOAR: bytecode weakness analysis, framework based fuzzers, manual source code review, and source code weakness analyzers. A quick manual search for catch (NullPointerException across a codebase shows every candidate. Then check each one against MITRE's three cases.
How to fix it
MITRE's mitigation: do not rely extensively on catching exceptions, especially to validate user input, since handling exceptions can decrease the performance of an application. Check for null directly.
String email = user == null ? null : user.getEmail();
String domain = "unknown";
if (email != null) {
int at = email.indexOf('@');
if (at >= 0 && at + 1 < email.length()) {
domain = email.substring(at + 1);
}
}
Java's Optional and annotations such as nullability checks in your build can also make null handling explicit.
Quick check
Is it ever fine to catch NullPointerException?
MITRE accepts it in a test harness that feeds unexpected input to the classes under test. In production code, check for null instead.