ADVERTISEMENT
ADVERTISEMENT

C# program to demonstrate the stack overflow exception

Here, we are going to learn about the stack overflow exception and demonstrating the example of stack overflow exception in C#.
Submitted by Nidhi, on September 16, 2020

Here we demonstrate the stack overflow exception using infinite recursive call.

Program:

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# program to demonstrate the multiple catch blocks

using System;

class ExceptionDemo
{
    static void Main(string[] args)
    {
        int num1=0;
        int num2=0;
        int num3=0;
        
        try
        {
            Console.Write("Enter the value of num1: "); 
            num1 = int.Parse(Console.ReadLine());

            Console.Write("Enter the value of num2: ");
            num2 = int.Parse(Console.ReadLine());

            num3 = num1 / num2;

            Console.WriteLine("Num3 : " + num3);
        }
        catch (DivideByZeroException exp)
        {
            Console.WriteLine(exp.Message);
        }
        catch (FormatException)
        {
            Console.WriteLine("Exception: Invalid format");
        }
        catch (Exception)
        {
            Console.WriteLine("Other exception generated");
        }
    }
}

Output:

Process is terminated due to StackOverflowException.
Press any key to continue . . .

Explanation:

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 »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.