Why does this “finally” execute?

2019-01-23 13:35发布

If you run the code below it actually executes the finally after every call to the goto:

    int i = 0;
Found:
    i++;
    try
    {
        throw new Exception();
    }
    catch (Exception)
    {
        goto Found;
    }
    finally
    {
        Console.Write("{0}\t", i);
    }

Why?

8条回答
狗以群分
2楼-- · 2019-01-23 14:04

Because a finally statement is expected to execute after leaving the try (or catch when an exception is caught). This includes when you make your goto call.

查看更多
相关推荐>>
3楼-- · 2019-01-23 14:05

Why do you expect it to not execute?

If you have try/catch/finally or try/finally block, finally block executes no matter what code you may have in the try or catch block most of the time.

Instead of goto, consider 'return'.

//imagine this try/catch/finally block is inside a function with return type of bool. 
try
{
    throw new Exception();
}
catch (Exception)
{
    return false; //Let's say you put a return here, finally block still executes.
}
finally
{
    Console.WriteLine("I am in finally!");
}
查看更多
在下西门庆
4楼-- · 2019-01-23 14:05

The gist of the answers given - that when control leaves the protected region via any means, whether "return", "goto", "break", "continue" or "throw", the "finally" is executed - is correct. However, I note that almost every answer says something like "the finally block always runs". The finally block does NOT always run. There are many situations in which the finally block does not run.

Who wants to try to list them all?

查看更多
Fickle 薄情
5楼-- · 2019-01-23 14:05

That's by design. In the exception handler you can take some exception-specific action. In the finally block you should do resource cleanup - that's why the finally block is always executed no matter what the exception handling code is.

查看更多
贪生不怕死
6楼-- · 2019-01-23 14:12

As people have mentioned, finally runs no matter the program flow. Of course, the finally block is optional, so if you don't need it, don't use it.

查看更多
我欲成王,谁敢阻挡
7楼-- · 2019-01-23 14:14

The following text comes from the C# Language Specification (8.9.3 The goto statement)


A goto statement is executed as follows:

  • If the goto statement exits one or more try blocks with associated finally blocks, control is initially transferred to the finally block of the innermost try statement. When and if control reaches the end point of a finally block, control is transferred to the finally block of the next enclosing try statement. This process is repeated until the finally blocks of all intervening try statements have been executed.
  • Control is transferred to the target of the goto statement.
查看更多
登录 后发表回答