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.
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.4.50327.0
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.