Updated April 13, 2023
Introduction to C# OutOfMemoryException
OutOfMemoryException in C# is an exception that is thrown by the .NET framework execution engine when the program does not have enough memory to continue its execution. As its name suggests this exception will occur in our program when the CLR i.e. Common Language Runtime will not be able to allocate enough memory which will be required to perform certain operations of our program.
This exception does not always mean that we do not have enough space available in memory but sometimes it means that we do not have enough contiguous memory which is required by our program for allocation.
Syntax
The syntax to catch an OutOfMemoryException in C# is as follows:
try
{
//user code which can throw OutOfMemoryException
}
catch(OutOfMemoryException exception)
{
//statements to handle the exception
}
The syntax to throw an OutOfMemoryException in C# is as follows:
throw new OutOfMemoryException();
In the above statement ‘throw’ is the keyword which is used to throw exceptions in C#.
How OutOfMemoryException works in C#?
In C#, we get OutOfMemoryException when our program does not have enough space to continue its execution. There could be many reasons for getting this exception. We also encounter this exception when in total we have enough space for our program to execute but this space is not contiguous for the allocations required to be done by our program. The two major reasons for this exception are as follows:
Trying to increase the length of a StringBuilder object beyond the length which is specified by the MaxCapacity property of StringBuilder.
We will get the exception saying “Insufficient memory to continue the execution of the program.”
- When we are making an assignment or calling a method that requires memory allocation and at the same time the CLR is not able to provide enough contiguous memory for our allocation then we will get OutOfMemoryException.
The other reasons which can become the cause of this exception include:
- Running the application on a 32-bit system which has only 2GB of virtual memory due to which CLR finds it difficult to provide contiguous memory for the allocations required by the application.
- After working with unmanaged resources like file handlers, database connections, pointers, etc. if we do not dispose of these resources then it leads to a memory leak which in result degrades the performance of our application and can lead to OutOfMemoryException.
- Working with large data sets requires a huge amount of memory and if CLR does not have enough contiguous space available for it then it results in OutOfMemoryException.
- As strings are immutable, the operations performed on string create a new string in the memory. So if we are working with large strings and if we are performing concatenation operation repeatedly on the string then it can lead to multiple memory allocations which in result will degrade the performance of our application and can become a cause of OutOfMemoryException.
- If we have pinned multiple objects in the memory for a very long period then it becomes difficult for the garbage collector to provide contiguous memory allocation to these objects.
Examples
Here are the following examples mention below
Example #1
Example showing OutOfMemoryException thrown by the program when we try to expand the StringBuilder object beyond its maximum capacity.
Code:
using System;
using System.Text;
public class Program
{
public static void Main()
{
StringBuilder stringBuilder = new StringBuilder(17, 17);
stringBuilder.Append("Welcome to the ");
try
{
stringBuilder.Insert(0, "world of C# programming", 1);
Console.WriteLine(stringBuilder.ToString());
Console.ReadLine();
}
catch (OutOfMemoryException exception)
{
Console.WriteLine(exception.Message);
Console.ReadLine();
}
}
}
Output:
Example #2
Example showing a program that encounters OutOfMemoryException while trying to add the element in the list where the number of elements to be added is more than the capacity of the list.
Code:
using System;
using System.Text;
using System.Collections.Generic;
namespace ConsoleApp4
{
public class Program
{
public static void Main()
{
try
{
string[] strArray = GetArray();
Console.WriteLine(strArray);
Console.ReadLine();
}
catch (OutOfMemoryException exception)
{
Console.WriteLine(exception);
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
public static string[] GetArray()
{
List<string> strList = new List<string>();
for (int i = 0; i <= int.MaxValue; i++)
{
strList.Add("Hello");
}
return strList.ToArray();
}
}
}
Output:
How to avoid OutOfMemoryException in C#?
We can avoid OutOfMemoryException in C# by keeping in mind the following points:
- To avoid this exception while working with StringBuilder, we can call the constructor StringBuilder.StringBuilder(Int32, Int32) and can set the MaxCapacity property to a value that will be large enough to serve the accommodation required when we expand the corresponding StringBuilder object.
- To avoid this exception while working on a 32-bit system, we can recompile our application from 32 bit to 64-bit system in visual studio by below steps:
- Menu Bar -> Build -> Configuration Manager
- Click on the list of Active Solution Platform and select the 64-bit platform and then click on the Close button.
If the 64-bit platform is not available in the list then:
- Click on New option from the list
- On the New Solution Platform Window, click on the ‘Type or select the new platform’ list and then select the ‘x64’ option.
- Click on the OK button.
- To avoid getting this exception while working with unmanaged resources, we should always call Dispose() method after completing our work with the unmanaged resource which is no longer required.
- To avoid this exception while working with large data sets, we should try to filter the data and then should pass only the required data for processing.
- To avoid this exception while working with large strings or while performing large string concatenation, we can make use of StringBuilder instead of string because StringBuilder is mutable and does not create a new instance of the string when we perform any operation on it.
Conclusion
The OutOfMemoryException is a runtime exception that tells the programmer that there is no enough memory or there is a lack of contiguous memory for the allocations required by the C# program.
To avoid this exception the user should always take necessary precautions and should handle this exception.
Recommended Articles
This is a guide to C# OutOfMemoryException. Here we discuss how OutOfMemoryException works in C# along with the programming examples. You may also have a look at the following articles to learn more –