Tuesday, April 29, 2008

Trivia: How does CLR create a OutOfMemoryException



When the system goes out of memory a OutOfMemoryException is thrown. Similarly for stack overflow a StackOverFlorException is thrown. Now typically an exception is thrown as follows (or the corresponding native way)

throw new System.OutOfMemoryException();

But when the system is already out of memory there's a little chance that creating an exception object will succeed. So how does the CLR create these exception objects?

The answer is trivial and as expect, at the very application start it creates all these exception objects and stores them in a static list. In case these exceptions are to be thrown then it is fetched from this list and thrown.

The consequence of handling Stack overflow is even bigger because once the stack has overflown calling even a single method in that thread is equally dangerous and can cause further corruption. That is the material for another post :)

No comments: