如何用 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP