Home >Backend Development >C#.Net Tutorial >How to catch out of memory exception in C#?
System.OutOfMemoryException occurs when the CLR cannot allocate enough memory required.
System.OutOfMemoryException inherits from the System.SystemException class.
Setting up the string -
string StudentName = "Tom"; string StudentSubject = "Maths";
Now you need to initialize with the allocated capacity i.e. the length of the initial value -
StringBuilder sBuilder = new StringBuilder(StudentName.Length, StudentName.Length);
Now if you try to insert an additional value then An exception will occur.
sBuilder.Insert(value: StudentSubject, index: StudentName.Length - 1, count: 1);
The following exception occurred -
System.OutOfMemoryException: Out of memory
To catch the error, try the following code -
Live Demo
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); } } } }
Above Handles the OutOfMemoryException and generates the following error -
Error: System.OutOfMemoryException: Out of memory
The above is the detailed content of How to catch out of memory exception in C#?. For more information, please follow other related articles on the PHP Chinese website!