Home
Search
C# OutOfMemoryExceptionUnderstand the OutOfMemoryException, which occurs when not enough memory is available.
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.
Exception
GC.Collect
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.
IL
MemoryFailPoint. The OutOfMemoryException may be predicted in advance with the MemoryFailPoint class. This type will indicate if the memory can be allocated.
MemoryFailPoint
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.
Home
© 2007-2022 sam allen.
see site info on the changelog.