如何捕獲 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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP