Mike Baxter
Mike Baxter

Reputation: 7268

Why can't control leave a finally statement?

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?

Upvotes: 65

Views: 26602

Answers (3)

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

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.

Upvotes: 27

Ohad Schneider
Ohad Schneider

Reputation: 38122

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.
}

Upvotes: -10

Alex
Alex

Reputation: 7919

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.

Upvotes: 95

Related Questions