If I return out of a try/finally block in C# does the code in the finally always run?

前端 未结 4 549
醉梦人生
醉梦人生 2020-12-05 06:46

It seems like it does as per some initial testing, but what I\'d like to know is if it is guaranteed to return or if in some cases it can not return? This i

4条回答
  •  失恋的感觉
    2020-12-05 07:47

    Anything in a finally block will always be executed regardless of what happens inside the try or catch blocks. It doesn't matter if you return from the method or not.

    The only exception to this is if the code in the finally block throws an exception, then it will stop executing like any other block of code.

    In regards to goto, the answer is still yes. Consider the following code:

    try
    {
        Console.WriteLine("Inside the Try");
        goto MyLabel;
    }
    finally
    {
        Console.WriteLine("Inside the Finally");
    }
    
    MyLabel:
        Console.WriteLine("After the Label");
    

    The output produced is this:

    Inside the Try

    Inside the Finally

    After the Label

提交回复
热议问题