rspec/rules/S1696/csharp/rule.adoc
2020-12-23 14:59:06 +01:00

44 lines
1.0 KiB
Plaintext

``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.
== 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;
}
----
== See
* http://cwe.mitre.org/data/definitions/395.html[MITRE, CWE-395] - Use of NullPointerException Catch to Detect NULL Pointer Dereference
* https://wiki.sei.cmu.edu/confluence/x/_TdGBQ[CERT, ERR08-J.] - Do not catch NullPointerException or any of its ancestors