Exceptions thrown under Activator.CreateInstance do not break the debugger [VS2012]

Consider the following code:

public class ActivatorTest
{
public ActivatorTest()
{
throw new Exception();
}
}

ActivatorTest activatorTest = (ActivatorTest)Activator.CreateInstance(typeof(ActivatorTest));

When this is run on Xamarin.Android or Xamarin.iOS in VS2012, the debugger breaks at the call to Activator.CreateInstance with the following message: "Unhandled Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation."

When I run this same code in a WP8 project, the debugger breaks at the original thrown exception.

Why is this? And is there any way I can get VS to break when the original exception is thrown? These issues are trivial to figure out on WP8, but a pain to track down in Xamarin projects.

Posts

  • ChrisHonselaarChrisHonselaar NLBeta ✭✭✭
    edited June 2013

    Actually, the behavior you see in Xamarin.iOS and Xamarin.Android is perfectly normal and exactly the same as in vanilla Console, WPF, Winforms, Silverlight etc applications.

    From the debugger's point of view, breaking at the CreateInstance() call is arguably correct. You are not calling the ActivatorTest() constructor - you are synthetically constructing an instance. Somewhere internally of course, the runtime ends up calling the constructor, but this is effectively outside of the visible scope of your code entirely.

    Think about it - CreateInstance() simply expects a type to instance out of thin air, and that type could be anything - even including a type you created at runtime! What would the debugger possibly point to in that case, except the CreateInstance() call?

    The actual exception within the constructor is still bubbled up, by the way - it's not lost, you simply do not get the break location. Just look for the InnerException property on the TargetInvocationException you are getting.

    The exception here would appear to be WP8. Perhaps MS added some new fancy-pants debugger there, or implemented Activator in a different way.

  • This makes sense - thank you for the explanation Chris!

Sign In or Register to comment.