10

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.

akjoshi
  • 15,374
  • 13
  • 103
  • 121
Alexander Bartosh
  • 8,287
  • 1
  • 21
  • 22
  • I run the code above and was not able to reproduce the issue - it works as expected, exception is caught – sergtk Jun 03 '12 at 17:25
  • Please check that you have Code Contracts Runtime Contract Checking enabled for you project and you build Release configuration. I you still cant reproduce it please let me know the version of code contracts you are using. Thanks – Alexander Bartosh Jun 04 '12 at 08:16
  • reproducable with 1.4.50327.0. Weird :-O – sergtk Jun 05 '12 at 03:42

1 Answers1

25

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.

Community
  • 1
  • 1
Alexander Bartosh
  • 8,287
  • 1
  • 21
  • 22