2021-01-27 13:42:22 +01:00
``++NullReferenceException++`` should be avoided, not caught. Any situation in which ``++NullReferenceException++`` 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.
2020-06-30 12:47:33 +02:00
== Noncompliant Code Example
----
public int GetLengthPlusTwo(string str)
{
int length = 2;
try
{
length += str.Length;
}
catch (NullReferenceException e)
{
log.info("argument was null");
}
return length;
}
----
== Compliant Solution
----
public int GetLengthPlusTwo(string str)
{
int length = 2;
if (str != null)
{
length += str.Length;
}
else
{
log.info("argument was null");
}
return length;
}
----
2020-12-21 15:38:52 +01:00
== See
* http://cwe.mitre.org/data/definitions/395.html[MITRE, CWE-395] - Use of NullPointerException Catch to Detect NULL Pointer Dereference
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)
include::message.adoc[]
include::highlighting.adoc[]
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[]
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]