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

查看:119
本文介绍了为什么.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?

在测试这个code请阅读以下问题的答案。

Before testing this code please read the answer below.

推荐答案

这是因为你有code运行时合同合同检查项目中的属性使您使用Release配置。如果你是,你SafeMethodWillNeverThrow()方法转换为用code的帮助下,下列合同重写:

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)
    {
    }
}

哎哟!

结论:你在你所看到的不信任 - 读IL:)

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

这个问题是可重复使用下面的code合同版本:

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

我使用code合同,并希望尽快有错误修复。 我已经贴吧<一href="http://social.msdn.microsoft.com/Forums/en-US/$c$ccontracts/thread/e2b9b734-2d6e-432b-9735-b3a2b6316c8c">$c$c合同论坛。把它尽快解决的唯一办法就是吸引足够的关注。所以,请投了,特别是在code合同论坛

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

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

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