如何用 C# 捕獲記憶體異常?
當 CLR 無法分配足夠所需的記憶體時,就會發生 System.OutOfMemoryException。
System.OutOfMemoryException 從 System.SystemException 類繼承而來。
設定字串 -
string StudentName = "Tom"; string StudentSubject = "Maths";
現在,你需要使用分配的容量(即初始值的長度)進行初始化 -
StringBuilder sBuilder = new StringBuilder(StudentName.Length, StudentName.Length);
現在,如果你要嘗試插入附加值,就會發生異常。
sBuilder.Insert(value: StudentSubject, index: StudentName.Length - 1, count: 1);
發生以下異常 -
System.OutOfMemoryException: Out of memory
要捕獲錯誤,可以嘗試下面的程式碼 -
示例
using System; using System.Text; namespace Demo { class Program { static void Main(string[] args) { try { string StudentName = "Tom"; string StudentSubject = "Maths"; StringBuilder sBuilder = new StringBuilder(StudentName.Length, StudentName.Length); // Append initial value sBuilder.Append(StudentName); sBuilder.Insert(value: StudentSubject, index: StudentName.Length - 1, count: 1); } catch (System.OutOfMemoryException e) { Console.WriteLine("Error:"); Console.WriteLine(e); } } } }
上述處理 OutOfMemoryException 並生成以下錯誤 -
輸出
Error: System.OutOfMemoryException: Out of memory
廣告