views:

164

answers:

2

OK, I admit it this code will just look weird to you, and that's because it is weird. This is just code to reproduce the behavior, not code I want to use.

class Program
{
    static void Main(string[] args)
    {
        try
        {
            Activator.CreateInstance(typeof(Func<int>), new object[] { new object(), IntPtr.Zero });
        }
        catch
        {
            Console.WriteLine("This won't print!");
        }

        Console.Write("Actually this will not print either!");
        Console.ReadLine();
    }
}

No matter what exception type I try to catch (the actual exception thrown is an ArgumentException as far as I can tell) the code inside the catch block will not execute. Actually execution will just stop at the Activator.CreateInstance-line.

+1  A: 

When I run this code in .NET 3.5 I get a ExecutionEngineException. When the runtime throws this exception it is similar to calling Environment.FailFast. Apparently this is a symptom of memory corruption on the heap.

When I switch your example code to the following the correct behavior is achieved.

Activator.CreateInstance(
    typeof(Func<int>), 
    new object[] { IntPtr.Zero, new object() }
);

I am well aware that this brings up more questions than answers... :)

ChaosPandion
I'm not able to catch the exception and inspect it at all, what are your settings to achieve this?
Patrik Hägne
@Patrik - What version of .NET are you running?
ChaosPandion
3.5 using VS 2008.
Patrik Hägne
@Patrik - You may want to check out what options you have set under **Debug->Exceptions**.
ChaosPandion
@ChaosPandion, yes I did check "thrown" for all types of exception from the get go but it doesn't break anyway. Not sure if I'm missing some other setting???
Patrik Hägne
@Patrik - This is just a theory but try adding `(Exception ex)` to your `catch` clause.
ChaosPandion
+2  A: 

You've bombed the CLR with that code. Impressive. The actual mishap is corruption of the garbage collected heap, it is signaled with an ExecutionEngineException. Apparently the damage is extensive enough to prevent the CLR from executing the exception handler.

You can report this at connect.microsoft.com. However, the bug is fixed in .NET 4.0, it generates the proper exception, ArgumentNullException, "Value cannot be null, Parameter name: method". The workaround is obvious, don't pass IntPtr.Zero when it expects a non-null string.

Hans Passant