Empty Try Block

ID

csharp.empty_try_block

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

CSharp

Tags

CWE:1071, reliability

Description

Reports try statements whose body is empty. An empty try block guards no code, so its catch and finally clauses can never react to a real failure. The construct is dead code and only adds noise to the source.

Rationale

A try with an empty body is almost always a leftover from refactoring: the protected code was moved or deleted but the surrounding try/catch stayed behind. Readers are misled into thinking error handling is in place when nothing is actually guarded.

public class Loader
{
    public void Broken()
    {
        try                       // FLAW — the try body is empty, the catch can never fire
        {
        }
        catch (IOException)
        {
            Recover();
        }
    }

    public void Ok()
    {
        try                       // OK — the try guards real work
        {
            ReadFile();
        }
        catch (IOException)
        {
            Recover();
        }
    }
}

Remediation

Move the code that may throw into the try body, or remove the empty try/catch/finally construct entirely if it no longer guards anything.