如何在 C# 中捕获内存不足异常?
csharpprogrammingserver side programming更新于 2025/5/29 6:37:17
当 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:内存不足
要捕获错误,请尝试以下代码 −
示例
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);
// 附加初始值
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

