为什么.net异常没有被抓住? [英] Why .net exception is not caught?

查看:159
本文介绍了为什么.net异常没有被抓住?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下安全程序:

internal class Safe
{
    public static void SafeMethodWillNeverThrow()
    {
        try
        {
            var something = ThrowsNewException();
            Func<int, string> x = p => something.ToString();
        }
        catch (Exception)
        {
        }
    }

    private static object ThrowsNewException() 
    {
        throw new Exception();
    }

    public static void Main()
    {
        SafeMethodWillNeverThrow();
    }
}

它不应该有异常完成。
但是为什么当我运行它失败?
为什么SafeMethodWillNeverThrow()抛出异常?

It should never complete with an exception. But why it fails when I run it? Why SafeMethodWillNeverThrow() throws the Exception?

在测试此代码之前,请阅读以下答案。

Before testing this code please read the answer below.

推荐答案

这是因为您在项目属性中启用了Code Contracts Runtime Contract Checking启用了Release配置。如果你是,你的SafeMethodWillNeverThrow()方法在代码合同重写器的帮助下转换为以下内容:

It is because you have Code Contracts Runtime Contract Checking enabled in your project properties you use Release configuration. And if you are, your SafeMethodWillNeverThrow() method gets converted to the following with the help of Code Contracts rewriter:

public static void SafeMethodWillNeverThrow()
{
    object something = ThrowsNewException();
    try
    {
        Func<int, string> func1 = p => something.ToString();
    }
    catch (Exception)
    {
    }
}

Ouch!

结论:不要相信你看到的 - 读IL:)。

Conclusion: Do not trust in what you see - read IL :).

以下代码合约版本可重现此问题:

The issue is reproducible with following Code Contracts versions:


  1. 1.4.50327.0

  2. 1.4.50126.1

  1. 1.4.50327.0
  2. 1.4.50126.1

我正在使用代码合同,并希望尽快修复错误。
我已经发布到。解决问题的唯一办法就是吸引足够的注意力。所以请投票,特别是在代码合同论坛上

I am using Code Contracts and would like to have the error fixed ASAP. I have posted it to Code Contracts forum. The only way to have it fixed soon is to attract enough attention to it. So please vote up, especially on the Code Contracts forum

更新2016年5月:

版本1.9.10714.2给出不同的异常
未处理的异常:System.InvalidProgramException:公共语言运行时检测到无效的程序。

Version 1.9.10714.2 gives a different exception Unhandled Exception: System.InvalidProgramException: Common Language Runtime detected an invalid program.

这篇关于为什么.net异常没有被抓住?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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