dotnet runtime_exception ai_generated true

System.StackOverflowException

ID: dotnet/stackoverflow

Also available as: JSON · Markdown
80%Fix Rate
85%Confidence
55Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
8 active

Root Cause

StackOverflowException occurs when the execution stack overflows due to infinite recursion or excessively deep call chains. This exception cannot be caught in .NET. Common causes include recursive property setters, circular DI dependencies, and recursive serialization. Fix by identifying and breaking the recursive cycle.

generic

Workarounds

  1. 85% success Identify and break the recursive cycle in the call chain
    Examine the stack trace (visible in the crash dump) to find the repeating method pattern. Common causes: a property setter that assigns to itself (this.Name = Name instead of field = value), AutoMapper/serializer circular references, or recursive method missing a base case. Fix the recursion termination condition or break the cycle
  2. 88% success Convert recursive algorithms to iterative with an explicit stack
    Replace recursive method calls with a Stack<T> or Queue<T> data structure and a while loop. For example, replace recursive tree traversal with: var stack = new Stack<Node>(); stack.Push(root); while (stack.Count > 0) { var node = stack.Pop(); /* process and push children */ }

Dead Ends

Common approaches that don't work:

  1. Attempting to catch StackOverflowException with try-catch 95% fail

    StackOverflowException is not catchable in .NET since .NET 2.0; the CLR terminates the process immediately when the stack overflows, so no catch block will execute

  2. Increasing the thread stack size via Thread constructor or environment variable 80% fail

    Only delays the crash for truly recursive code; infinite recursion will exhaust any stack size. Larger stacks also waste memory per thread and can cause OutOfMemoryException in multi-threaded scenarios

Error Chain

Leads to:
Preceded by:
Frequently confused with: