rspec/rules/S1696/csharp/rule.adoc
2024-03-06 16:10:30 +01:00

52 lines
1.7 KiB
Plaintext

== Why is this an issue?
Catching `NullReferenceException` is generally considered a bad practice because it can hide bugs in your code. Instead of catching this exception, you should aim to prevent it. This makes your code more robust and easier to understand.
In addition, constantly catching and handling `NullReferenceException` can lead to performance issues. Exceptions are expensive in terms of system resources, so they should be used cautiously and only for exceptional conditions, not for regular control flow.
== How to fix it
Instead of catching NullReferenceException, it's better to prevent it from happening in the first place. You can do this by using null checks or null conditional operators (`?.`) before accessing members of an object.
=== Code examples
==== Noncompliant code example
[source,csharp,diff-id=1,diff-type=noncompliant]
----
public int GetLengthPlusTwo(string str)
{
try
{
return str.Length + 2;
}
catch (NullReferenceException e)
{
return 2;
}
}
----
==== Compliant solution
[source,csharp,diff-id=1,diff-type=compliant]
----
public int GetLengthPlusTwo(string str)
{
if (str is null)
{
return 2;
}
return str.Length + 2;
}
----
== Resources
=== Documentation
* CWE - https://cwe.mitre.org/data/definitions/395[CWE-395 - Use of NullPointerException Catch to Detect NULL Pointer Dereference]
* Microsoft Learn - https://learn.microsoft.com/en-us/dotnet/api/system.nullreferenceexception[NullReferenceException class]
* Microsoft Learn - https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators#null-conditional-operators\--and-[Null-conditional operators ?. and ?[\]]
include::../rspecator.adoc[]