C Sharp

Using the StackTrace Property

Another useful property of the System.Exception class is the StackTrace property. The StackTrace property enables you to determine-at any given point at which you have a valid System.Exception object-what the current call stack looks like. Take a look at the following code: -

using System;
class StackTraceTestApp
{
    public void Open(String fileName)
    {
        Lock(fileName);
        // ...
    }
    public void Lock(String fileName)
    {
        // Error condition raised.
        throw new Exception("failed to lock file");
    }
    public static void Main()
    {
        StackTraceTestApp test = new StackTraceTestApp();
        try
        {
            test.Open("c:\\test.txt");
            // Use file.
        }
        catch(Exception e)
        {
            Console.WriteLine(e.StackTrace);
        }
    }
}

In this example, what prints out is the following: -

at StackTraceTest.Main()

Therefore, the StackTrace property returns the call stack at the point that the exception is caught, which can be useful for logging and debugging scenarios.