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