2023-05-03 11:06:20 +02:00
== Why is this an issue?
2023-10-16 16:34:38 +02:00
``++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.
2021-09-21 15:40:35 +02:00
2023-10-16 16:34:38 +02:00
=== 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;
}
----
2021-09-21 15:40:35 +02:00
2023-05-03 11:06:20 +02:00
== Resources
2021-09-21 15:40:35 +02:00
2024-01-15 17:15:56 +01:00
* CWE - https://cwe.mitre.org/data/definitions/395[CWE-395 - Use of NullPointerException Catch to Detect NULL Pointer Dereference]
2021-09-21 15:40:35 +02:00
* https://tinyurl.com/y6r4amg3[CERT, ERR08-J.] - Do not catch NullPointerException or any of its ancestors
2021-06-02 20:44:38 +02:00
2021-06-03 09:05:38 +02:00
ifdef::env-github,rspecator-view[]
2021-09-20 15:38:42 +02:00
'''
== Implementation Specification
(visible only on this page)
2023-10-16 16:34:38 +02:00
=== Message
Make the dereference of XXX conditional on its not being null
2021-09-20 15:38:42 +02:00
2021-06-08 15:52:13 +02:00
'''
2021-06-02 20:44:38 +02:00
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
2023-06-22 10:38:01 +02:00
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]