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.
Yes. Something "exceptional" has happened, and your program does not know how to handle it, so it must stop execution at that point and "crash". There will be code that is executed after the crash, such as finally blocks, but basically the party is over for your code.
When code reports an error, an exception cannot be caught if the thread has not yet entered a try-catch block. For example, syntaxError, because the syntax exception is reported in the syntax checking phase, the thread execution has not entered the try-catch code block, naturally cannot catch the exception.
When the debugger breaks, it shows you where the exception was thrown. You can also add or delete exceptions. With a solution open in Visual Studio, use Debug > Windows > Exception Settings to open the Exception Settings window. Provide handlers that respond to the most important exceptions.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With