#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}]",



About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #905 – Examining an Exception’s Stack Trace

  1. Pingback: Dew Drop – August 11-12, 2013 (#1,601) | Alvin Ashcraft's Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: