How to throw exception without resetting stack trace?

dance2die picture dance2die · Apr 8, 2009 · Viewed 26k times · Source

This is a follow-up question to Is there a difference between “throw” and “throw ex”?

is there a way to extract a new error handling method without resetting the stack trace?

[EDIT] I will be trying both "inner method" and another answer provided by Earwicker and see which one can work out better to mark an answer.

Answer

Adam Robinson picture Adam Robinson · Apr 8, 2009

Yes; That's what the InnerException property is for.

catch(Exception ex)
{
    throw new YourExceptionClass("message", ex);
}

This will allow you to add your own logic, then throw your own exception class. The StackTrace of the YourExceptionClass instance will be from within this code block, but the InnerException will be the exception you caught, with the StackTrace it had before.