The exception that is thrown when the execution stack overflows because it contains too many nested method calls. This class cannot be inherited.
See Also: StackOverflowException Members
StackOverflowException is thrown for execution stack overflow errors, typically in case of a very deep or unbounded recursion. The System.Reflection.Emit.OpCodes.Localloc Microsoft intermediate language (MSIL) instruction throws StackOverflowException.
StackOverflowException uses the HRESULT COR_E_STACKOVERFLOW, which has the value 0x800703E9. For a list of initial property values for a StackOverflowException object, see the StackOverflowException.#ctor constructors.
The value of the inherited Exception.Data property is always null.
In prior versions of the .NET Framework, your application could catch a StackOverflowException object (for example, to recover from unbounded recursion). However, that practice is currently discouraged because significant additional code is required to reliably catch a stack overflow exception and continue program execution.
Starting with the .NET Framework version 2.0, a StackOverflowException object cannot be caught by a try-catch block and the corresponding process is terminated by default. Consequently, users are advised to write their code to detect and prevent a stack overflow. For example, if your application depends on recursion, use a counter or a state condition to terminate the recursive loop. Note that an application that hosts the common language runtime (CLR) can specify that the CLR unload the application domain where the stack overflow exception occurs and let the corresponding process continue. For more information, see ICLRPolicyManager and Hosting the Common Language Runtime.
The following example demonstrates an error that causes a StackOverflowException exception.
C# Example
using System; public class StackOverflowExample { public static void recursion() { recursion(); } public static void Main() { try { recursion(); } catch(StackOverflowException e) { Console.WriteLine("Error caught: {0}", e); } } }
The output is
Error caught: System.StackOverflowException: Exception of type System.StackOverflowException was thrown.