Why can't a 'continue' statement be inside a 'finally' block?

后端 未结 11 780
情深已故
情深已故 2020-12-23 02:38

I don\'t have a problem; I\'m just curious. Imagine the following scenario:

foreach (var foo in list)
{
    try
    {
         //Some code
    }
    catch (E         


        
11条回答
  •  半阙折子戏
    2020-12-23 03:20

    The designers of the language simply didn't want to (or couldn't) reason about the semantics of a finally block being terminated by a control transfer.

    One issue, or perhaps the key issue, is that the finally block gets executed as part of some non-local control transfer (exception processing). The target of that control transfer isn't the enclosing loop; the exception processing aborts the loop and continues unwinding further.

    If we have a control transfer out of the finally cleanup block, then the original control transfer is being "hijacked". It gets canceled, and control goes elsewhere.

    The semantics can be worked out. Other languages have it.

    The designers of C# decided to simply disallow static, "goto-like" control transfers, thereby simplifying things somewhat.

    However, even if you do that, it doesn't solve the question of what happens if a dynamic transfer is initiated from a finally: what if the finally block calls a function, and that function throws? The original exception processing is then "hijacked".

    If you work out the semantics of this second form of hijacking, there is no reason to banish the first type. They are really the same thing: a control transfer is a control transfer, whether it the same lexical scope or not.

提交回复
热议问题