Reading and Preserving C# Exception Stack Traces
Learn how to read, log, and preserve C# exception stack traces, handle async stack traces, and understand the role of PDB files.

When an exception is thrown in C#, the runtime captures a snapshot of the call stack at that moment. That snapshot is exposed through the StackTrace property of the Exception class. Reading it correctly, and preserving it through rethrows, is essential for debugging and production observability.
What the StackTrace Property Actually Contains
The StackTrace property returns a string that represents the frames at the point where the exception was thrown. Each frame typically includes the method name, the declaring type, and, when debug symbols are available, the source file and line number. The property is populated when the exception is thrown; if you create an exception with new Exception() and never throw it, StackTrace is null.
The exact format depends on the runtime and on the presence of PDB files. Without PDBs, the stack trace still shows method names but omits file and line information. The string is human-readable, but not structured. For programmatic analysis, parse it or use the StackTrace class from System.Diagnostics, which provides a structured view.
Reading the Stack Trace in Code
Accessing the stack trace is straightforward:
try
{
DoWork();
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}For structured access, use the StackTrace class:
catch (Exception ex)
{
var stackTrace = new StackTrace(ex, true);
foreach (var frame in stackTrace.GetFrames())
{
var method = frame.GetMethod();
var file = frame.GetFileName();
var line = frame.GetFileLineNumber();
Console.WriteLine($"{method?.DeclaringType?.FullName}.{method?.Name} at {file}:{line}");
}
}The StackTrace constructor overload with true requests file and line information from PDBs. This is useful when you need structured stack frames rather than a raw string, for example when sending them to a log aggregation system that expects JSON.
Preserving the Original Stack Trace When Rethrowing
One common mistake is rethrowing with throw ex;. That resets the stack trace to the current location and loses the original origin. The correct way to rethrow without losing the original stack trace is throw; inside a catch block:
try
{
DoWork();
}
catch (Exception ex)
{
// Log the exception
throw; // Preserves original stack trace
}If you need to rethrow the original exception after leaving a catch block, or preserve it for later, use ExceptionDispatchInfo from System.Runtime.ExceptionServices:
ExceptionDispatchInfo.Capture(ex).Throw();This rethrows the original exception object with its original stack trace intact, which is useful when you cannot use throw; because the rethrow happens outside the original catch block.
Parsing Stack Traces for Logging and Diagnostics
Raw stack trace strings are convenient for human reading but awkward for automated analysis. You can parse the string, but the format is culture-sensitive and can vary across runtimes. A more robust approach is to use the StackTrace class, which gives you StackFrame objects.
When logging a stack trace, storing structured frames rather than the raw string allows you to filter, group, or search by method name in your log system. For example, you might ignore frames from framework code or focus only on your application's assembly:
var frames = new StackTrace(ex, true).GetFrames()
.Where(f => f.GetMethod()?.DeclaringType?.Assembly == typeof(Program).Assembly);This filtering is often more useful than a raw string dump, especially in large applications with deep framework call stacks.
Stack Traces in Async and Await Code
Async methods can produce misleading stack traces. The compiler rewrites an async method into a state machine, so while the method runs, the original caller is no longer on the call stack. If an exception is thrown after an await, the captured trace may not show the call site that invoked the async method. In older .NET versions, the generated MoveNext frame often hid the logical method name.
Starting with .NET Core 2.1, the compiler and runtime can surface the original async method name and line information when PDBs are available, but generated state machine frames can still appear. The exact behavior depends on the runtime version and compiler.
If you need to preserve the original exception context when an exception crosses an async or helper-method boundary, use ExceptionDispatchInfo. For production diagnostics, log the exception with its InnerException and the full stack trace rather than trying to simplify it manually.
Why Line Numbers Depend on PDB Files
Stack traces include source file names and line numbers only when the corresponding PDB files are available at runtime. PDBs are generated during compilation and map IL instructions back to source lines. In release builds, PDBs are often not deployed to production, so stack traces show method names but no line numbers. This is a common source of confusion when debugging production issues.
To get line numbers in production, deploy the PDB files alongside the assemblies. Many CI/CD pipelines include PDBs in the deployment package. Alternatively, Source Link stores repository metadata in the PDB so debugging tools can fetch the matching source file when needed. The decision to include PDBs in production is a tradeoff between artifact size and diagnostic value; for most applications, the benefit of line numbers outweighs the small size increase.
Performance Cost of Capturing Stack Traces
Capturing a stack trace is not free. The runtime records frame information when an exception is thrown, and rendering the readable StackTrace string can add further work when you access it. Throwing exceptions in normal control flow is discouraged not only because it disrupts flow but also because it adds overhead.
If you are in a hot path and need to log errors, consider whether you need the full stack trace every time. For example, you might log the exception message and only capture the stack trace for a subset of failures. Alternatively, you can use Environment.StackTrace to get the current stack without an exception, but that also has a cost. Be deliberate about when you capture stack traces, especially in high-throughput services.
The exact behavior of when the stack string is formatted can depend on the runtime version. In practice, the overhead is acceptable for exceptional conditions, but exceptions should not be used as a control-flow mechanism.
When logging stack traces, consider the volume. Logging a full stack trace for every handled exception can flood your log system and obscure the real issues. Use structured logging to record the exception type, message, and stack trace as separate fields, and apply filtering or sampling where appropriate. This keeps the diagnostic value while controlling storage and processing costs.
Try matching browser tools
All toolsSmall utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related C# guides
All C# guidesC# Dispose vs Destructor: Key Differences Explained
c# dispose vs destructor: Understand the difference between Dispose and destructors in C#, when each runs, and how to manage unmanaged resources correctly.
C# Variable Declaration: Syntax and Practical Usage
Learn how to declare variables in C# with explicit types, var, and nullable annotations, and understand how defaults, scope, and readability affect your choices.
C# Primary Constructors for Classes: Syntax and Usage
Learn how to use C# primary constructors for classes: syntax, initialization, dependency injection, and limitations with practical examples.
C# IComparer: Custom Sorting with IComparer<T>
Learn how to implement IComparer<T> in C# to define custom sort order for arrays and lists, handle nulls, and avoid common performance pitfalls.
More in C#
All C# guidesThe guides filed next to this one in C#, in library order.