加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – CLR中的错误? CLR执行引擎失败

发布时间:2020-12-16 01:53:21 所属栏目:百科 来源:网络整理
导读:使用AFAIK,try和finally块执行一段可能引发异常的代码,如果我们准备处理某种类型的异常和/或除了它们之外我们还添加了catch块,比如FileIOException,AccessRight等.但是当我跑这个.. private void button1_Click(object sender,EventArgs e) { try { Environm
使用AFAIK,try和finally块执行一段可能引发异常的代码,如果我们准备处理某种类型的异常和/或除了它们之外我们还添加了catch块,比如FileIOException,AccessRight等.但是当我跑这个..

private void button1_Click(object sender,EventArgs e)
    {
        try
        {
            Environment.FailFast("It failed");
        }
        finally
        {
            MessageBox.Show("Done");
        }
    }

它打破了一个例外并说

检测到FatalExecutionEngineError
消息:运行时遇到致命错误.错误的地址位于线程0xd04处的0x032526f4处.错误代码是0x80131623.此错误可能是CLR中的错误,也可能是用户代码的不安全或不可验证部分中的错误.此错误的常见来源包括COM-interop或PInvoke的用户编组错误,这可能会破坏堆栈.

现在msdn说

Usually,when an unhandled exception ends an application,whether or
not the finally block is run is not important. However,if you have
statements in a finally block that must be run even in that situation,
one solution is to add a catch block to the try-finally statement.

所以,我添加了catch块,但它仍然说同样的事情.

private void button1_Click(object sender,EventArgs e)
    {
        try
        {
            Environment.FailFast("It failed");
        }
        catch (Exception ex)
        {

        }
        finally
        {
            MessageBox.Show("Done");
        }
    }

它再次失败并出现同样的错误.至于CLR说最终总是运行代码块(至少在添加catch时),情况肯定不是这样.评论/意见谁?

还有这里的快照..

解决方法

这是设计的. Environment.FailFast的目的是立即停止执行.通过设计,它不会在catch或finally块中运行任何代码.

documentation说:

This method terminates a process without running any active
try/finally blocks or finalizers.

The FailFast method writes the message string to the Windows
Application event log,creates a dump of your application,and then
terminates the current process. The messa string is also included in
error reporting to Microsoft.

Use the FailFast method instead of the Exit method to terminate your
application if the state of your application is damaged beyond repair,
and executing your application’s try/finally blocks and finalizers
will corrupt program resources.

这清楚表明finally块中的代码不会运行.如果有一种方法可以在Environment.FailFast之后运行代码,那么会使Environment.FailFast变得毫无用处.它的存在是基于您调用它后代码不执行的事实.

你指出的文件(强调我的):

Usually,when an unhandled exception ends an application,whether or not the finally block is run is not important. However,if you have statements in a finally block that must be run even in that situation,one solution is to add a catch block to the try-finally statement.

但这些话根本不适用于此.您假设在调用Environment.FailFast时,未处理的异常终止应用程序.事实并非如此.该应用程序刚刚在现场终止 – 没有未处理的异常.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读