4

An Exception object has a StackTrace property on it. But it is just a string.

Is there a way to get an actual System.Diagnostics.StackTrace object from an Exception?

I ask because I am getting the Exception object from an UnhandledExceptionEventHandler and I don't have access to the frame that generated the exception to get an actual Stack Trace.

3
  • 2
    Using some of the StackTrace constructors with Exception argument? e.g. new StackTrace(ex). Commented Dec 5, 2016 at 19:18
  • This question seems related; if true your stack trace is gone already and you need to fix any throw ex calls. Note that if this is the case, then @IvanStoev's answer shouldn't work because the ex is already missing the stack trace so I don't think the StackTrace constructor will find anything to copy. See here for how to re-throw an exception without losing the stack trace in .NET 4.5+. Commented Dec 5, 2016 at 19:23
  • @Quantic - thank you for the response, but PALMERALE's and IvenStoev's solution seems to work great. Commented Dec 5, 2016 at 19:46

1 Answer 1

6
try{
//some code
}
catch (Exception ex){
   System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(ex);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Works perfectly! Adding , true after the ex gets you the file info too!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.