Will finally blocks be executed if returning from try or catch blocks in C#? If so, before returning or after?

前端 未结 4 1265
猫巷女王i
猫巷女王i 2020-12-15 23:25

No content available!

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-16 00:25

    Yes, the finally block is executed however the flow leaves the try block - whether by reaching the end, returning, or throwing an exception.

    From the C# 4 spec, section 8.10:

    The statements of a finally block are always executed when control leaves a try statement. This is true whether the control transfer occurs as a result of normal execution, as a result of executing a break, continue, goto, or return statement, or as a result of propagating an exception out of the try statement.

    (Section 8.10 has a lot more detail on this, of course.)

    Note that the return value is determined before the finally block is executed though, so if you did this:

    int Test()
    {
        int result = 4;
        try
        {
            return result;
        }
        finally
        {
            // Attempt to subvert the result
            result = 1;
        }
    }
    

    ... the value 4 will still be returned, not 1 - the assignment in the finally block will have no effect.

提交回复
热议问题