## 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

    public int GetLengthPlusTwo(string str)
    {
        try
        {
            return str.Length + 2;
        }
        catch (NullReferenceException e)
        {
            return 2;
        }
    }

#### Compliant solution

    public int GetLengthPlusTwo(string str)
    {
        if (str is null)
        {
            return 2;
        }
        return str.Length + 2;
    }

## Resources

### Documentation

- CWE - CWE-395 - Use of NullPointerException Catch to Detect NULL Pointer Dereference
- Microsoft Learn - NullReferenceException class
- Microsoft Learn - Null-conditional operators ?. and ?[]