C# - StackOverflowException Exception Example

Learn about the stack overflow exception and demonstrating the example of stack overflow exception in C#. By Nidhi Last updated : April 03, 2023

StackOverflowException Exception

Here, we are demonstrating the stack overflow exception using infinite recursive call.

C# program to demonstrate the StackOverflowException exception

The source code to demonstrate the stack overflow exception is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

// C# - StackOverflowException Exception Example

using System;

class ExceptionDemo {
  static void PrintNumbers(int value) {
    Console.WriteLine("The value is: " + value);

  static void Main() {
    try {
    } catch (StackOverflowException e) {


The value is: 0
The value is: 1
The value is:2
Process is terminated due to StackOverflowException.
Press any key to continue . . .


In the above program, we created a class ExceptionDemo that contains two methods increaseVal() and Main(). The increaseVal() is a recursive method, here we increase the value of the parameter, due to recursion, method calls indefinitely then StackOverflowException exception get generated by the program that will be caught by "catch" block and print exception message on the console screen.

C# Exception Handling Programs »

Comments and Discussions!

Copyright © 2023 www.includehelp.com. All rights reserved.