Wednesday, November 30, 2005

Catching Stack Overflow Exceptions

Here's something to be aware of if you are using unmanaged STL collections within .NET: Craig, a new member of our development team, found some interesting behavior when catching stack overflow exceptions from C++.

Craig was working on an managed assembly using a STL collection that had been wrapped with a C++ managed wrapper. The managed wrapper had a method which recursively navigated through all the outward bound references of the object, inserting objects into the unmanaged STL collection. As you can probably guess, deep navigations of objects with many out references could cause a stack overflow. The STL collection was throwing a StackOverflowException, and all of the TRY/CATCH blocks in managed code were being ignored, no matter how global the exception handlers were.

I would have thought that a normal exception handler could handle this scenario. However, he reports that stack overflow exceptions can only be caught by structured exception handlers. Normal C++ exception handlers or managed exception handlers will totally ignore the stack overflow exception.

There are solutions to this, such as putting structured exception handlers that either rethrow a System.StackOverflowException or attempt to handle it in the __except block.

Be sure to read Catching Stack Overflow Exceptions, part 2 for more SEH fun!

No comments: