最终执行时间的定义 [英] Definition of when finally is executed

查看:83
本文介绍了最终执行时间的定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复项:
最终无法在.net try..finally阻止
在C#中,如果抛出未处理的异常,将在try,catch中最终执行finally块吗?

http://en.wikipedia.org/wiki/comparison_of_C_Sharp_and_Java#Finally_Blocks_and_Uncaught_Exceptions 指出 finally 块并不总是运行.错了吧?

http://en.wikipedia.org/wiki/Comparison_of_C_Sharp_and_Java#Finally_Blocks_and_Uncaught_Exceptions states that the finally block doesn't always run. That's wrong, right?

CLI的ECMA标准(C#从中推导其异常功能)指出,在堆栈的两次遍历搜索中处理了异常.[13]第一遍尝试查找匹配的catch块,如果找不到,则终止程序.仅当找到匹配的catch块时,第二遍才会执行,第二遍将运行中间的finally块.这样就可以诊断问题,而无需首先通过finally块修改程序状态.它还消除了当程序处于未知状态(例如外部数据损坏或引发其他异常)时,finally块可能具有不良副作用的风险.

The ECMA standard for the CLI (from which C# derives its exception features) states that exceptions are handled in a two-pass search of the stack.[13] The first pass attempts to locate a matching catch block, and terminates the program if none is found. Only if a matching catch block is found does the second pass execute, which runs the intervening finally blocks. This allows the problem to be diagnosed without the program state first being modified by the finally blocks; it also eliminates the risk that finally blocks may have undesirable side-effects when the program is in an unknown state (such as corruption of external data, or throwing further exceptions).

但是,我不需要捕获即可最终执行:

But, I don't need a catch to finally execute:

    static void Main()
    {
        try { throw new Exception(); }
        finally
        {
            Console.WriteLine("1");
        }
    }

推荐答案

我注意到没有人真正回答过您的问题,即此文本正确吗?"

I notice that no one has actually answered your question, which is "is this text correct?"

不,这是不正确的,因为它忽略了重要的一点.

No, it is not correct, in that it omits an important point.

CLI规范中未引用的相关部分是分区I的12.4.2节,其中指出:

The relevant portion of the CLI specification which it fails to quote is section 12.4.2 of Partition I, which states:

最终处理程序...应为每当块退出时执行,不管是否发生正常的控制流程或未处理的流程

A finally handler ... shall be executed whenever the block exits, regardless of whether that occurs by normal control flow or by an unhandled exception.


现在,正如其他人指出的那样,这里有一些微妙之处.请注意,该规范明确指出了当块退出时将最终执行.如果程序因故障快速终止,堆栈溢出或有人将电源线从墙上拔出而终止,则该块永远不会退出!该程序可以在该块退出之前 终止,因此最终将无法运行.


Now, as others have noted, there are some subtleties here. Notice that the specification clearly calls out that the finally is executed when the block exits. If the program is terminated by a failfast, by a stack overflow, or by someone pulling the power cord out of the wall, then the block never exits! The program could be terminated before the block exits, and therefore the finally would not run.

这篇关于最终执行时间的定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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