Skip to main content

Control cannot leave the body of a finally clause

In This Article

CodeRush Classic shows the Control cannot leave the body of a finally clause code issue if a finally block includes statements redirecting the program execution flow out of this block (e.g. return, goto, continue).

#Fix

Remove the invalid statement out of the finally block.

#Purpose

Highlights the execution flow redirecting statements, which would cause the Control cannot leave the body of a finally clause compilation error.

#Example

public string Data { get; private set; }
public bool LoadData()
{
    try
    {
        Data = File.ReadAllText("myText.txt");
    }
    catch (Exception ex)
    {
        Console.WriteLine("Loading failure");
        return false;
    }
    finally
    {
        Console.WriteLine("Loading finished");return true;
    }
}

Fix:

public string Data { get; private set; }
public bool LoadData()
{
    try
    {
        Data = File.ReadAllText("myText.txt");
    }
    catch (Exception ex)
    {
        Console.WriteLine("Loading failure");
        return false;
    }
    finally
    {
        Console.WriteLine("Loading finished");
    }
    return true;
}