OutOfMemoryException. Memory is limited. The OutOfMemoryException is triggered by allocation instructions. It is thrown by the .NET Framework execution engine.
Exception notes. This C# exception can occur during any allocation call during runtime. With MemoryFailPoint, we can protect against this exception.
In this example, we allocate a string that is extremely large. But the OutOfMemoryException is thrown by the runtime because this is not possible.
Note The intention of the program is to demonstrate the exception itself. After the program, we note ways to deal with the exception.
class Program
{
static void Main()
{
// Attempt to create a string of 2.1 billion chars.// ... This results in an out-of-memory error.// ... It would require 4.2 billion bytes (4 gigabytes).
string value = new string('a', int.MaxValue);
}
}Unhandled Exception: OutOfMemoryException.
Instructions. There are 3 IL instructions that can raise this exception: the box, newarr, and newobj instructions. These all perform allocation.
MemoryFailPoint. The OutOfMemoryException may be predicted in advance with the MemoryFailPoint class. This type will indicate if the memory can be allocated.
A summary. We saw a program that attempts to allocate memory, but this fails and throws the OutOfMemoryException. This exception can be thrown during any allocation instruction.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Aug 3, 2022 (edit link).