Home
C#
StackOverflowException
Updated Sep 26, 2022
Dot Net Perls
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 26, 2022 (edit).
Home
Changes
© 2007-2025 Sam Allen