How to capture out of memory exception in C#?

The System.OutOfMemoryException occurs when the CLR fails to allocate sufficient memory for an operation. This exception is inherited from the System.SystemException class and can be caught using try-catch blocks to handle memory allocation failures gracefully.

Common scenarios that trigger this exception include attempting to create very large arrays, working with StringBuilder objects that exceed their capacity, or processing extremely large datasets.

Syntax

Following is the syntax for catching OutOfMemoryException

try {
   // Code that might throw OutOfMemoryException
} catch (OutOfMemoryException ex) {
   // Handle the exception
   Console.WriteLine("Memory allocation failed: " + ex.Message);
}

Using StringBuilder with Fixed Capacity

One way to trigger an OutOfMemoryException is by exceeding the maximum capacity of a StringBuilder object −

using System;
using System.Text;

class Program {
   static void Main(string[] args) {
      try {
         string StudentName = "Tom";
         string StudentSubject = "Maths";
         
         // Create StringBuilder with fixed capacity equal to StudentName length
         StringBuilder sBuilder = new StringBuilder(StudentName.Length, StudentName.Length);
         sBuilder.Append(StudentName);
         
         // This will throw OutOfMemoryException as it exceeds capacity
         sBuilder.Insert(value: StudentSubject, index: StudentName.Length - 1, count: 1);
         
      } catch (OutOfMemoryException e) {
         Console.WriteLine("Error:");
         Console.WriteLine(e.Message);
      }
   }
}

The output of the above code is −

Error:
Out of memory

Using Large Array Allocation

Another common scenario is attempting to allocate extremely large arrays −

using System;

class Program {
   static void Main(string[] args) {
      try {
         // Attempt to create a very large array
         int[] largeArray = new int[int.MaxValue];
         Console.WriteLine("Array created successfully");
         
      } catch (OutOfMemoryException ex) {
         Console.WriteLine("Memory allocation failed:");
         Console.WriteLine(ex.Message);
      } catch (OverflowException ex) {
         Console.WriteLine("Array size overflow:");
         Console.WriteLine(ex.Message);
      }
   }
}

The output of the above code is −

Memory allocation failed:
Out of memory

Handling Multiple Memory Operations

Here's a more comprehensive example that demonstrates multiple scenarios where OutOfMemoryException might occur −

using System;
using System.Text;

class MemoryExceptionHandler {
   static void Main(string[] args) {
      // Test StringBuilder capacity limit
      TestStringBuilderCapacity();
      
      // Test large string concatenation
      TestLargeStringOperation();
   }
   
   static void TestStringBuilderCapacity() {
      try {
         StringBuilder sb = new StringBuilder(5, 5);
         sb.Append("Hello");
         sb.Append(" World"); // This exceeds capacity
         
      } catch (OutOfMemoryException ex) {
         Console.WriteLine("StringBuilder capacity exceeded:");
         Console.WriteLine(ex.Message);
      }
   }
   
   static void TestLargeStringOperation() {
      try {
         string result = "";
         for (int i = 0; i < 1000000; i++) {
            result += "This is a memory intensive operation ";
         }
         
      } catch (OutOfMemoryException ex) {
         Console.WriteLine("Large string operation failed:");
         Console.WriteLine(ex.Message);
      }
   }
}

The output of the above code is −

StringBuilder capacity exceeded:
Out of memory
Large string operation failed:
Out of memory

Best Practices for Memory Management

  • Use using statements for disposable objects to ensure proper cleanup.

  • Avoid creating unnecessary large objects or arrays.

  • Consider using streaming approaches for large data processing.

  • Monitor memory usage and implement proper exception handling.

Conclusion

The OutOfMemoryException in C# occurs when the CLR cannot allocate sufficient memory for an operation. Use try-catch blocks to handle these exceptions gracefully and implement proper memory management practices to minimize their occurrence in your applications.

Updated on: 2026-03-17T07:04:35+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements