I have a C# program on Visual Studio 2012 that has an error. How can I retrieve the stack trace?
3 Answers
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.
If you get an Exception, you can get a StackTrace by calling the member of the same name.
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;
}
}