Why .net exception is not caught?

◇◆丶佛笑我妖孽 提交于 2019-11-27 23:49:29

问题


Consider the following "Safe" program:

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();
    }
}

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.


回答1:


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!

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

    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

Update May 2016:

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



来源:https://stackoverflow.com/questions/10866307/why-net-exception-is-not-caught

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!