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?
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.
It's by design and it's described in C# specification:
It is a compile-time error for a
break,continue, orgotostatement to transfer control out of afinallyblock. When abreak,continue, orgotostatement occurs in afinallyblock, the target of the statement must be within the samefinallyblock, or otherwise a compile-time error occurs.It is a compile-time error for a
returnstatement to occur in afinallyblock.
Also, from C# 6.0 spec draft on MSDN:
It is a compile-time error for a
returnstatement to occur in afinallyblock.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With