CLR Stack Unwinding, SEH (Structured Exception Handling) & Cost of Throwing
1Concept
Throwing an exception in C# captures the entire thread stack trace and unwinds call frames through two-pass Structured Exception Handling (SEH). Never use exceptions for normal control flow.
2Architecture Diagram
Throw Exception
│
[ Phase 1: Search Pass ] ──> Traverses call stack to find matching catch handler
│
[ Phase 2: Unwind Pass ] ──> Executes finally blocks & unwinds thread stack frames3Code Example
C# 13 & .NET 9
using System;
public class ExceptionCostDemo
{
public static void Main()
{
// Bad: Exception as control flow (Takes ~2,000-5,000ns)
// Good: TryParse pattern (Takes ~5ns)
string rawNumber = "12345";
if (int.TryParse(rawNumber, out int parsed))
{
Console.WriteLine($"Successfully parsed in O(1) without exception: {parsed}");
}
}
}4Expected Output
Successfully parsed in O(1) without exception: 12345
5Key Takeaways
- ✓Throwing an exception is ~1000x slower than returning a `Result<T>` or `bool`.
- ✓Always follow the `Tester-Doer` or `Try-Parse` design patterns.
- ✓Use exceptions exclusively for truly exceptional, unrecoverable system failures.