以下文章提供了 C# StackOverflowException 的概述。 StackOverflowException 由称为 OpCodes.LocalLoc 指令的 Microsoft 中间语言 (MSIL) 指令引发。 StackOverflowException 类提供了多种方法,包括 StackOverflowException()、StackOverflowException(string message)、StackOverflowException(string message,Exception innerException) 等。
语法:
[Serializable] public sealed class StackOverflowException : SystemException
下面给出的是提到的示例:
C# 程序,用于演示运行时发生无限递归时的堆栈溢出异常。
代码:
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); } }
输出:
C# 程序演示 StackOverflowException,即使在使用 try 块和 catch 代码块捕获异常后,运行时发生无限递归时也是如此。
代码:
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); } } }
输出:
递归的无限循环首先将零作为参数传递给 try 块中的 ex 方法。尽管我们写了catch块来捕获异常,但它无法捕获这个异常,因为这个异常超出了catch块的捕获范围。
以上是C# StackOverflowException的详细内容。更多信息请关注PHP中文网其他相关文章!