Why can't control leave a finally statement?

C#Try Catch

C# Problem Overview


When I place a return inside the block of a finally statement, the compiler tells me:

> Control cannot leave the body of a finally clause

Example:

try
{
}
catch
{
}
finally
{
    return;
}

Why is this?

C# Solutions


Solution 1 - C#

Consider what would happen if you were to return 1 inside the try block and return 0 inside the finally block... Your function would be trying to return two values! The combined options of try and catch are exhaustive in terms of control flow.

Solution 2 - C#

It's by design and it's described in C# specification:

> It is a compile-time error for a break, continue, or goto statement to > transfer control out of a finally block. When a break, continue, or > goto statement occurs in a finally block, the target of the statement > must be within the same finally block, or otherwise a compile-time > error occurs. > > It is a compile-time error for a return statement to > occur in a finally block.

Also, from C# 6.0 spec draft on MSDN:

> It is a compile-time error for a return statement to occur in a finally block.

Solution 3 - C#

Current answers explain why this happens well, but I also think it's important to note how easy it is to circumvent this constraint in the case where no return value is involved, and the finally clause is the last thing in the method (which happens often):

try {}
catch {}
finally
{
    FinallyMethod();
}

Then in FinallyMethod you can use return statements as much as you'd like

void FinallyMethod()
{
   //...
   if (x == y)
       return;
   else
       a = b;
   //etc.
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMike BaxterView Question on Stackoverflow
Solution 1 - C#AlexView Answer on Stackoverflow
Solution 2 - C#MarcinJuraszekView Answer on Stackoverflow
Solution 3 - C#Ohad SchneiderView Answer on Stackoverflow