Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

จะจับข้อยกเว้นหน่วยความจำใน C # ได้อย่างไร


System.OutOfMemoryException เกิดขึ้นเมื่อ CLR ล้มเหลวในการจัดสรรหน่วยความจำเพียงพอที่จำเป็น

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