#905 – Examining an Exception’s Stack Trace

When you access an exception object’s StackTrace property from within an exception handler, you only have access to a single multiline string that dumps out details about the stack.

For example:


This format is not ideal, since it’s fairly verbose and you have no ability to look at individual items within the stack.

If you want more control in formatting output that shows the stack, or you want to programmatically examine the stack, you can create a new System.Diagnostics.StackTrace object, passing it the Exception object that you’re handling.

Below is an example that dumps out a more abbreviated version of the stack and changes the order to match the calling sequence.

                catch (Exception ex)
                    Console.WriteLine("** Caught exception, stack :");
                    StackTrace stack = new StackTrace(ex);
                    StackFrame[] frames = stack.GetFrames();
                    for (int i = frames.Count() - 1; i >= 0; i--)
                        MethodBase mb = frames[i].GetMethod();
                        Console.WriteLine("- {0}  [{1}]",