Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't control leave a finally statement?

Tags:

c#

try-catch

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?

like image 751
Mike Baxter Avatar asked Apr 16 '13 08:04

Mike Baxter


2 Answers

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.

like image 193
Alex Avatar answered Oct 12 '22 17:10

Alex


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.

like image 43
MarcinJuraszek Avatar answered Oct 12 '22 17:10

MarcinJuraszek