Why can't I get a meaningful exception with Activator.CreateInstan

G

Guest

I have a class where I throw an exception in the constructor like this

class Foo
{
Foo constructor
{
throw new Exception("custom exception")
}
}

I create an instance of this class with Activator.CreateInstance in a try
catch block

try
{
Activator.CreateInstance(typeofFoo)
}
catch (e)
{
}

When I inspect this exception, it is a reflection exception, not my custom
exception that I threw from inside the class constructor. Is there something
I can do to get access to my exception, instead of the reflection exception
created by the framework. Inspecting the stack trace shows the origin of the
error to be Activator.CreateInstance, where it should be in the Foo
constructor.
 
J

Jon Skeet [C# MVP]

Harry Keck said:
I have a class where I throw an exception in the constructor like this

class Foo
{
Foo constructor
{
throw new Exception("custom exception")
}
}

I create an instance of this class with Activator.CreateInstance in a try
catch block

try
{
Activator.CreateInstance(typeofFoo)
}
catch (e)
{
}

When I inspect this exception, it is a reflection exception, not my custom
exception that I threw from inside the class constructor. Is there something
I can do to get access to my exception, instead of the reflection exception
created by the framework. Inspecting the stack trace shows the origin of the
error to be Activator.CreateInstance, where it should be in the Foo
constructor.

Use the InnerException property of the exception that CreateInstance
throws.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top