Cannot throw exception from Activator.CreateInstance

Well, I admit that this code will look strange to you, and that is because it is strange . This is just code to reproduce the behavior, not the 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 type of exception I'm trying to catch (the actual exception is an ArgumentException, as far as I can tell), the code inside the catch block will not execute. In fact, execution will simply be stopped on the Activator.CreateInstance line.

+7
c # exception-handling activator
source share
2 answers

You bombed the CLR with this code. Impressive. The actual error is damage to garbage collected by the garbage; it is signaled by an ExecutionEngineException. The damage seems to be extensive enough so that the CLR does not execute the exception handler.

You can report it on connect.microsoft.com. However, the bug was fixed in .NET 4.0, it throws the correct exception, ArgumentNullException, "Value cannot be null, Parameter name: method". The workaround is obvious, don't skip IntPtr.Zero when it expects a non-empty string.

+4
source share

When I run this code in .NET 3.5, I get an ExecutionEngineException . When the runtime throws this exception, it looks like a call to Environment.FailFast . This is apparently a symptom of memory corruption in the heap.

When I switch your sample code to the following, the correct behavior will be achieved.

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

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

+1
source share

All Articles