11

I am writing a component which, at the top level, invokes a method via reflection. To make my component easier to use, I'd like to catch any exceptions thrown by the invoked method and unwrap them.

Thus, I have something like:

try { method.Invoke(obj, args); }
catch (TargetInvocationException ex) {
    throw ex.InnerException;
}

However, this blows away the inner exception stack trace. I can't use just throw here (because I'm rethrowing a different exception object). What can I do in my catch block to make sure that the original exception type, message, and stack trace all get through?

Dusty
  • 3,946
  • 2
  • 27
  • 41
ChaseMedallion
  • 20,860
  • 17
  • 88
  • 152

1 Answers1

34

As answered here, starting with .NET 4.5 you can use the ExceptionDispatchInfo class to unwrap the inner exception.

try
{
    someMethod.Invoke();
}
catch(TargetInvocationException ex)
{
    ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
}
Community
  • 1
  • 1
Dusty
  • 3,946
  • 2
  • 27
  • 41