
Inline adoc files when they are included exactly once. Also fix language tags because this inlining gives us better information on what language the code is written in.
70 lines
1.3 KiB
Plaintext
70 lines
1.3 KiB
Plaintext
== Why is this an issue?
|
|
|
|
``++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
|
|
|
|
[source,csharp]
|
|
----
|
|
public int GetLengthPlusTwo(string str)
|
|
{
|
|
int length = 2;
|
|
try
|
|
{
|
|
length += str.Length;
|
|
}
|
|
catch (NullReferenceException e)
|
|
{
|
|
log.info("argument was null");
|
|
}
|
|
return length;
|
|
}
|
|
----
|
|
|
|
=== Compliant solution
|
|
|
|
[source,csharp]
|
|
----
|
|
public int GetLengthPlusTwo(string str)
|
|
{
|
|
int length = 2;
|
|
|
|
if (str != null)
|
|
{
|
|
length += str.Length;
|
|
}
|
|
else
|
|
{
|
|
log.info("argument was null");
|
|
}
|
|
return length;
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
* https://cwe.mitre.org/data/definitions/395[MITRE, CWE-395] - Use of NullPointerException Catch to Detect NULL Pointer Dereference
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Do not catch NullReferenceException; test for null instead.
|
|
|
|
|
|
=== Highlighting
|
|
|
|
throw new NullReferenceException()
|
|
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
include::../comments-and-links.adoc[]
|
|
endif::env-github,rspecator-view[]
|