
In some cases, the `rule.adoc` at root of a rule is never included anywhere and thus is dead code. It's a maintenance cost by itself, but also it misses opportunities to inline code that seems used by two documents when in fact only one document is actually rendered. And this missed opportunity, in turn, stops us from applying the correct language tag on the code samples.
64 lines
1.3 KiB
Plaintext
64 lines
1.3 KiB
Plaintext
== Why is this an issue?
|
|
|
|
``++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
|
|
|
|
[source,java]
|
|
----
|
|
public int lengthPlus(String str) {
|
|
int len = 2;
|
|
try {
|
|
len += str.length();
|
|
}
|
|
catch (NullPointerException e) {
|
|
log.info("argument was null");
|
|
}
|
|
return len;
|
|
}
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,java]
|
|
----
|
|
public int lengthPlus(String str) {
|
|
int len = 2;
|
|
|
|
if (str != null) {
|
|
len += str.length();
|
|
}
|
|
else {
|
|
log.info("argument was null");
|
|
}
|
|
return len;
|
|
}
|
|
----
|
|
|
|
|
|
== Resources
|
|
|
|
* https://cwe.mitre.org/data/definitions/395[MITRE, CWE-395] - Use of NullPointerException Catch to Detect NULL Pointer Dereference
|
|
* https://tinyurl.com/y6r4amg3[CERT, ERR08-J.] - Do not catch NullPointerException or any of its ancestors
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Make the dereference of XXX conditional on its not being null
|
|
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
include::../comments-and-links.adoc[]
|
|
|
|
endif::env-github,rspecator-view[]
|