System.OutOfMemoryException xảy ra khi CLR không phân bổ đủ bộ nhớ cần thiết.
System.OutOfMemoryException được kế thừa từ lớp System.SystemException.
Đặt các chuỗi -
string StudentName = "Tom"; string StudentSubject = "Maths";
Bây giờ bạn cần khởi tạo với Dung lượng được phân bổ là độ dài của giá trị ban đầu -
StringBuilder sBuilder = new StringBuilder(StudentName.Length, StudentName.Length);
Bây giờ, nếu bạn cố gắng chèn giá trị bổ sung, thì ngoại lệ sẽ xảy ra.
sBuilder.Insert(value: StudentSubject, index: StudentName.Length - 1, count: 1);
Trường hợp ngoại lệ sau xảy ra -
System.OutOfMemoryException: Out of memory
Để khắc phục lỗi, hãy thử đoạn mã sau -
Ví dụ
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);
}
}
}
} Phần trên xử lý OutOfMemoryException và tạo ra lỗi sau -
Đầu ra
Error: System.OutOfMemoryException: Out of memory