如果从C#中的try或catch块返回,将会执行finally块如果是这样,返回还是之后? [英] Will finally blocks be executed if returning from try or catch blocks in C#? If so, before returning or after?

查看:141
本文介绍了如果从C#中的try或catch块返回,将会执行finally块如果是这样,返回还是之后?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

没有内容可用!

推荐答案

是的, finally 执行,但流程离开 try 块 - 无论是到达结束,返回还是抛出异常。

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

从C#4规范,第8.10节:

From the C# 4 spec, section 8.10:


当控件离开一个try
时,finally块的语句总是执行声明。这是真的,无论控制转移是由于正常的
执行的结果而发生的,因为执行break,continue,goto或return语句,或者作为
的结果,将异常传播出来尝试语句。

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.

(当然,第8.10节还有更多的细节。)

(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;
    }
}

...值仍然会返回,不是1 - 最终块中的赋值将无效。

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

这篇关于如果从C#中的try或catch块返回,将会执行finally块如果是这样,返回还是之后?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆