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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Aug 3, 2022 (edit link).