Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to catch exception from Activator.CreateInstance

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.

like image 237
Patrik Hägne Avatar asked May 10 '10 14:05

Patrik Hägne


1 Answers

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.

like image 85
Hans Passant Avatar answered Sep 29 '22 06:09

Hans Passant