Empty Finally Block

ID

csharp.empty_finally_block

Severity

info

Remediation Complexity

auto_fix

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

CSharp

Tags

CWE:1071, reliability

Description

Reports finally blocks whose body is empty. An empty finally runs no cleanup, so it is dead code that usually signals incomplete error handling or a cleanup step that was forgotten.

Rationale

A finally exists to run cleanup whether or not an exception was thrown. An empty one contributes nothing and frequently marks a spot where a developer intended to release a resource — closing a stream, unlocking a mutex — but never wrote the code.

public class Worker
{
    public void Broken()
    {
        var stream = Open();
        try
        {
            Use(stream);
        }
        finally                   // FLAW — the finally body is empty, the stream is never closed
        {
        }
    }

    public void Ok()
    {
        var stream = Open();
        try
        {
            Use(stream);
        }
        finally                   // OK — the finally releases the resource
        {
            stream.Dispose();
        }
    }
}

Remediation

Add the cleanup the finally was meant to perform, or remove the empty finally clause. Prefer a using statement when the resource is disposable.