Why can't control leave a finally statement?
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
, orgoto
statement to transfer control out of afinally
block. When abreak
,continue
, orgoto
statement occurs in afinally
block, the target of the statement must be within the samefinally
block, or otherwise a compile-time error occurs.It is a compile-time error for a
return
statement to occur in afinally
block.
Also, from C# 6.0 spec draft on MSDN:
It is a compile-time error for a
return
statement to occur in afinally
block.