The following article provides an outline for C# StackOverflowException. The StackOverflowException is thrown by the Microsoft Intermediate Language (MSIL) instruction called OpCodes.LocalLoc instruction. The StackOverflowException class provides several methods, including StackOverflowException(), StackOverflowException(string message), StackOverflowException(string message, exception innerexception), and so on.
Syntax :
[Serializable] public sealed class StackOverflowException : SystemException
Given below are the examples mentioned :
C# program to demonstrate Stack Overflow Exception when there is an infinite recursion happening at the run time.
Code:
using System; //a class called program is defined public class program { // a method called rec is defined which takes a value as parameter and increases its value by one static void Rec(int vals) { // since we have written a recursive loop and 0 is passed as a parameter, it ends in an infinite loop causing exception Console.WriteLine(vals); Rec(++vals); } //main method is called public static void Main() { //The rec method is called to start the infinite recursion Rec(0); } }
Output:
C# program to demonstrate StackOverflowException when there is an infinite recursion happening at the run time even after using try block and catch blocks of code to catch the exception.
Code:
using System; //a class called check is defined public class check { // a method called ex is defined which takes a value as parameter and increases its value by one static void ex(int equals) { Console.WriteLine(equals); ex(++equals); } //main method is called within which try and block methods are defined to catch the exception public static void Main() { try { //The ex method is called by passing zero as a parameter to start the infinite recursion ex(0); } catch (StackOverflowException ep) { Console.WriteLine(ep.Message); } } }
Output:
An infinite loop for recursion begins by passing zero as a parameter to the ex method within the try block. Even though we have written the catch block to catch the exception, it fails to catch this exception because this exception goes beyond the catch block to be caught.
The above is the detailed content of C# StackOverflowException. For more information, please follow other related articles on the PHP Chinese website!