0

I have a C# program on Visual Studio 2012 that has an error. How can I retrieve the stack trace?

1
  • You mean in the UI? Debug, Window, Stack Trace. But you have to have an exception first.
    – paparazzo
    Commented Feb 12, 2014 at 18:04

3 Answers 3

3

While debugging, the stacktrace is accessible as the "Call Stack" window. If you want the stacktrace of an exception you caught, it is accessible through the StackTrace member of the Exception you caught:

try
{
    [...]
}
catch (Exception ex)
{
    Console.Write(ex.StackTrace);
}

To add another useful example:

try
{
    [...]
}
catch (Exception ex)
{
    System.Diagnostics.Debug.Write(ex.StackTrace);
}

This will print to the Visual Studio debug console instead of the console window of your application.

1

If you get an Exception, you can get a StackTrace by calling the member of the same name.

1

This is some code I use to get details

if (e.Exception.InnerException != null)
{
    sb.AppendLine("InnerException");
    if (e.Exception.InnerException.Message == null)
    {
        sb.AppendLine("e.Exception.InnerException.Message == null");
    }
    else
    {
        sb.AppendLine("e.Exception.InnerException.Message = " + e.Exception.InnerException.Message);
    }
    if (!string.IsNullOrEmpty(e.Exception.InnerException.StackTrace))
    {
        sb.AppendLine("e.Exception.InnerException.StackTrace ");
        int count = 0;
        foreach (string line in e.Exception.InnerException.StackTrace.Split('\n'))
        {
            sb.AppendLine(line.Trim());
            count++;
            if (count > 10) break;
        }
    }
}
sb.AppendLine("OuterException");
if (e.Exception.Message == null)
{
    sb.AppendLine("e.Exception.Message == null");
}
else
{
    sb.AppendLine("e.Exception.Message = " + e.Exception.Message);
}
if (!string.IsNullOrEmpty(e.Exception.StackTrace))
{
    sb.AppendLine("e.Exception.StackTrace ");
    int count = 0;
    foreach (string line in e.Exception.StackTrace.Split('\n'))
    {
        sb.AppendLine(line.Trim());
        count++;
        if (count > 10) break;
    }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.