StackOverflowException
The stack has limited memory. It can overflow. Typically the StackOverflowException
is triggered by a recursive method that creates a deep call stack.
Basically any program that has deeply-nested calls, such as a recursive call, is at risk of a StackOverflowException
. The size of the stack depends on the operating system.
This program defines a method that causes an infinite recursion at runtime. The Recursive()
method calls itself at the end of each invocation.
StackOverflowException
is caused by an infinite or uncontrolled recursion.using System; class Program { static void Recursive(int value) { // Write call number and call this method again. // ... The stack will eventually overflow. Console.WriteLine(value); Recursive(++value); } static void Main() { // Begin the infinite recursion. Recursive(0); } }79845 79846 79847 79848 79849 79850 79851 Process is terminated due to StackOverflowException.
Exception
messageThe message "Process is terminated" is displayed. If you wrap the initial call to Recursive in a try-catch
block, you cannot catch the StackOverflowException
.
Tail
recursionThe Recursive method body here contains a single call to the same method in its final statement. This could be rewritten as a linear loop.
We tested a program that creates an infinite recursion to demonstrate the StackOverflowException
. This exception is a risk to all programs—even those that do not use recursion.