Skip to content

CA1508 false positive: "Avoid dead conditional code" incorrectly flags condition in multiple catch clause with exit scenarios #51059

@Neroro64

Description

@Neroro64

Version Used:

> dotnet --info

.NET SDK:
 Version:           9.0.305
 Commit:            3fc74f3529
 Workload version:  9.0.300-manifests.8510cfe7
 MSBuild version:   17.14.21+8929ca9e3

Runtime Environment:
 OS Name:     Windows
 OS Version:  10.0.26100
 OS Platform: Windows
 RID:         win-x64
 Base Path:   C:\Program Files\dotnet\sdk\9.0.305\

Steps to Reproduce:

public static void Test()
{
    const int MaxRetries = 2; 
    for (int i = 0; i < MaxRetries; i++)
    {
        try { }
        catch (IndexOutOfRangeException)
        {
            return;
        }
        catch (InvalidOperationException)
        {
            if (i == MaxRetries - 1)  // CA1508 incorrectly flags this as dead code
            {
                throw;
            }
        }
    }
}

The Roslyn analyzer rule CA1508 is incorrectly flagging conditional statements as "dead code" in retry loop patterns, when multiple catch clauses with exit point are present.

EDIT: Forgot to add, that if I swap the order of the two catch clauses there is no false positive warning.

Diagnostic Id:
[CA1508] 'i == MaxRetries - 1' is always 'false'. Remove or refactor the condition(s) to avoid dead code.

Expected Behavior:
The condition i == 2 is valid and reachable when the loop reaches its final iteration (i=2) and an InvalidOperationException is caught. The presence of multiple catch clauses should not affect this analysis.

Actual Behavior:
CA1508 reports "Avoid dead conditional code" suggesting the condition is never true, which is incorrect.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions