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

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

No content available!

4条回答
  •  渐次进展
    2020-12-16 00:09

    A finally block will always be executed and this will happen before returning from the method, so you can safely write code like this:

    try {
        return "foo";
    } finally {
        // This will always be invoked
    }
    

    or if you are working with disposable resources:

    using (var foo = GetFoo())
    {
        // foo is guaranteed to be disposed even if an exception is thrown
        return foo.Bar();
    }
    

提交回复
热议问题