为什么.net异常没有被捕获?

Ale*_*osh 10 .net exception-handling exception code-contracts

考虑以下"安全"计划:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

它永远不会以异常完成.但是为什么它在我运行时失败了?为什么SafeMethodWillNeverThrow()会抛出异常?

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

Ale*_*osh 25

这是因为您在项目属性中启用了"代码合同运行时合同检查",并使用了"发布"配置.如果您是,则在Code Contracts重写器的帮助下,您的SafeMethodWillNeverThrow()方法将转换为以下内容:

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

哎哟!

结论:不要相信你所看到的 - 阅读IL :).

该问题可通过以下代码合同版本重现:

  1. 1.4.50327.0
  2. 1.4.50126.1

    我正在使用代码合同,并希望尽快修复错误.我已将其发布到Code Contracts论坛.修复它的唯一方法是吸引足够的注意力.所以请投票,特别是在Code Contracts论坛上

2016年5月更新:

版本1.9.10714.2给出了一个不同的异常Unhandled Exception:System.InvalidProgramException:Common Language Runtime检测到一个无效的程序.