All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.plugins.csharp.S1696.html Maven / Gradle / Ivy

There is a newer version: 10.2.0.105762
Show newest version

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





© 2015 - 2024 Weber Informatics LLC | Privacy Policy