OutOfMemoryException
Memory is limited. The OutOfMemoryException
is triggered by allocation instructions. It is thrown by the .NET Framework execution engine.
Exception
notesThis 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.
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.
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.
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.