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.
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.