Home
Search
StackOverflowExceptionUnderstand the StackOverflowException, which is usually caused by recursive methods.
C#
This page was last reviewed on Sep 26, 2022.
StackOverflowException. The stack has limited memory. It can overflow. Typically the StackOverflowException is triggered by a recursive method that creates a deep call stack.
Nested methods. 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.
Exception
Example. This program defines a method that causes an infinite recursion at runtime. The Recursive() method calls itself at the end of each invocation.
Recursion
However The current C# compiler does not achieve this. Each method call frame (activation record) is kept on the stack memory.
And After nearly 80,000 invocations, the stack memory space is exhausted and the program terminates.
Info Usually, the 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 message. The message "Process is terminated" is displayed. If you wrap the initial call to Recursive in a try-catch block, you cannot catch the StackOverflowException.
Try
Catch
Tail recursion. The Recursive method body here contains a single call to the same method in its final statement. This could be rewritten as a linear loop.
And Such a loop could continue indefinitely because it requires constant space on the stack.
But The C# compiler was unable to apply this optimization, called tail recursion, in this program.
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 26, 2022 (edit).
Home
Changes
© 2007-2023 Sam Allen.