A NullReferenceException or IndexOutOfRangeException is caught instead of prevented

tx0/csharp:catch-null-referencerecommendedwarningreliability/error-handlingdepth fastsmell, cwe-395

What it finds

These exceptions signal a bug in the code that throws them; catching them hides the bug and may leave state half updated. A null check or a bounds check where the value is used says what is expected.

From the rule's source, catch_null_reference.rs.

Example from the rule's tests
using System; class Lookup{    string First(string[] items)    {        try        {            return items[0];        }        catch (IndexOutOfRangeException)tx0 reports: IndexOutOfRangeException is caught instead of prevented        {            return null;        }        catch (System.NullReferenceException)tx0 reports: NullReferenceException is caught instead of prevented        {            return null;        }    }}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/csharp:catch-null-reference" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/csharp:catch-null-reference] reason="..."

tx0 explain tx0/csharp:catch-null-reference shows the same in the terminal. Found a false positive? Report it.