Freigeben über


OutOfMemoryException is special

Consider the humble OutOfMemoryException and its most common usage. If it is thrown when the system is well and truly out of memory then how would the system allocate enough memory to create a new instance of OutOfMemoryException? Luckily this problem has a simple solution: OutOfMemoryException is allocated up front so it's available when it needs to be thrown.

The .NET runtime does first try to create a new OutOfMemoryException instance but if it fails it will fall back to the preallocated instance so there is always an exception available to be thrown.

Some other exceptions are preallocated: StackOverflowException, ExecutionEngineException, and ThreadAbortException.