Rule Definition
Catching NullReferenceException should not be used as an alternative to checks and assertions for preventing dereferencing a null pointer.
It's usually better to avoid a NullReferenceException than to handle it after it occurs. Handling an exception can make your code harder to maintain and understand, and can sometimes introduce other bugs.
Remediation
As a general practice avoid NullReferenceException.
Check if the variable is null before dereferencing it.
Violation Code Sample
public static void Main(string[] args)
{
Console.WriteLine("Enter name of person:");
Person p = findPerson(Console.ReadLine());
try
{
Console.WriteLine("Person is {0:D} years old", p.getAge());
}
catch (NullReferenceException e)
{
Console.WriteLine("Person not found.");
}
}
Fixed Code Sample
public static void Main(string[] args)
{
Console.WriteLine("Enter name of person:");
Person p = findPerson(Console.ReadLine());
if (p != null)
{
Console.WriteLine("Person is {0:D} years old", p.getAge());
}
else
{
Console.WriteLine("Person not found.");
}
}
Reference
https://cwe.mitre.org/data/definitions/395.html
https://docs.microsoft.com/en-us/dotnet/api/system.nullreferenceexception?view=netcore-3.1
Related Technologies
Technical Criterion
CWE-395 - Use of NullPointerException Catch to Detect NULL Pointer Dereference
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.