BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET Framework
.NET 2.0+

Obtaining a Stack Trace

Call stacks are used to control the flow of programs as methods and properties are executed and terminated. When adding diagnostic code, such as logging, to software it can be useful to examine the call stack for a thread or exception using a stack trace.

Obtaining a Stack Trace from an Exception

All exceptions include a StackTrace property, which returns a string containing limited information about the call stack at the time that the exception was thrown. If you want more information than provided by this string, you can pass the exception to a StackTrace constructor. The resultant StackTrace object will contain stack frames that describe the call stack at the time of the exception.

You can use one of two constructors depending upon the information that you require. For simple information about the call stack, pass the exception alone. If you wish to read the source code information, add a second, Boolean argument with a value of true.

The following sample code recursively calls a method, which throws an exception on the fifth invocation. This exception is captured and used to create a stack trace, details of which are sent to the console.

static void Main(string[] args)
{
    try { RecursiveCall(5); }
    catch (Exception ex)
    {
        ShowExceptionCallStack(ex);
    }
}

private static void RecursiveCall(int count)
{
    if (count > 0)
    {
        RecursiveCall(count - 1);
    }
    else
    {
        throw new Exception();
    }
}

private static void ShowExceptionCallStack(Exception ex)
{
    StackTrace trace = new StackTrace(ex, true);
    StackFrame[] frames = trace.GetFrames();
    foreach (StackFrame frame in frames)
    {
        MethodBase info = frame.GetMethod();
        Console.WriteLine("{0}.{1} line {2}"
            , info.ReflectedType.FullName
            , info.Name
            , frame.GetFileLineNumber());
    }
}

/* OUTPUT

Demo.Program.RecursiveCall line 33
Demo.Program.RecursiveCall line 29
Demo.Program.RecursiveCall line 29
Demo.Program.RecursiveCall line 29
Demo.Program.RecursiveCall line 29
Demo.Program.RecursiveCall line 29
Demo.Program.Main line 18

*/
4 November 2012