以下文章提供了 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中文網其他相關文章!