org.sonar.l10n.java.rules.squid.S1696.html Maven / Gradle / Ivy
NullPointerException
should be avoided, not caught. Any situation in which NullPointerException
is explicitly caught can easily be converted to a null
test, and any behavior being carried out in the catch block can easily be moved to the "is null" branch of the conditional.
Noncompliant Code Example
public int lengthPlus(String str) {
int len = 2;
try {
len += str.length();
}
catch (NullPointerException e) {
log.info("argument was null");
}
return len;
}
Compliant Solution
public int lengthPlus(String str) {
int len = 2;
if (str != null) {
len += str.length();
}
else {
log.info("argument was null");
}
return len;
}
See
- MITRE, CWE-395 - Use of NullPointerException Catch to Detect NULL Pointer Dereference
- CERT, ERR08-J - Do not catch NullPointerException or any of its ancestors
© 2015 - 2025 Weber Informatics LLC | Privacy Policy