14

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?

2
  • No need to place tags in your question title. Tagging correctly is sufficient. Commented Jul 9, 2013 at 18:19
  • Why do you think it makes it easier to confuse the stack trace? Commented Jul 9, 2013 at 18:58

1 Answer 1

37

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Should be marked as the answer. Had the same problem and it was driving me crazy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.