如何用 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

更新于: 20-6 月 -2020

1 千 + 浏览

开启你的 职业生涯

完成课程即可获得认证

开始
广告
© . All rights reserved.