CodeQL documentation

Poor error handling: catch of NullReferenceException

ID: cs/catch-nullreferenceexception
Kind: problem
Security severity: 
Severity: warning
Precision: very-high
Tags:
   - quality
   - reliability
   - correctness
   - error-handling
   - external/cwe/cwe-395
Query suites:
   - csharp-security-and-quality.qls

Click to see the query in the CodeQL repository

Catching NullReferenceException should not be used as an alternative to checks and assertions for preventing dereferencing a null pointer.

Recommendation

Check if the variable is null before dereferencing it.

Example

The following example class, findPerson returns null if the person is not found.

class CatchOfNullReferenceException
{
    public static Person findPerson(string name)
    {
        // ...
    }

    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.");
        }
    }
}

The following example has been updated to ensure that any null return values are handled correctly.

class CatchOfNullReferenceExceptionFix
{
    public static Person findPerson(string name)
    {
        // ...
    }

    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.");
        }
    }
}

References

  • Common Weakness Enumeration: CWE-395.

  • © GitHub, Inc.
  • Terms
  • Privacy
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy