如何捕獲 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

上次更新:2020 年 6 月 20 日

1K+ 瀏覽量

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.