3

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.

Vaccano
  • 78,325
  • 149
  • 468
  • 850
  • 2
    Using some of the `StackTrace` [constructors](https://msdn.microsoft.com/en-us/library/25h0kw08(v=vs.110).aspx) with `Exception` argument? e.g. `new StackTrace(ex)`. – Ivan Stoev Dec 05 '16 at 19:18
  • [This](http://stackoverflow.com/questions/21479762/exception-with-no-stack-trace-how) 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](http://stackoverflow.com/questions/57383/in-c-how-can-i-rethrow-innerexception-without-losing-stack-trace) for how to re-throw an exception without losing the stack trace in .NET 4.5+. – Quantic Dec 05 '16 at 19:23
  • @Quantic - thank you for the response, but PALMERALE's and IvenStoev's solution seems to work great. – Vaccano Dec 05 '16 at 19:46

1 Answers1

5
try{
//some code
}
catch (Exception ex){
   System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(ex);
}
PALMERALE
  • 415
  • 5
  • 11