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 <em>exception</em>) { //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.
- 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.
If the 64-bit platform is not available in the list then:
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.
The above is the detailed content of C# OutOfMemoryException. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

There are several ways to modify XML formats: manually editing with a text editor such as Notepad; automatically formatting with online or desktop XML formatting tools such as XMLbeautifier; define conversion rules using XML conversion tools such as XSLT; or parse and operate using programming languages such as Python. Be careful when modifying and back up the original files.
