Monday, December 01, 2008

SEHException and HRESULT

I write programs for Windows using a mix of managed and unmanaged code. The interface between the two is uncomfortable and problematic for so many reasons it deserves its own blog.

When an unmanaged exception occurs and crosses back to the managed world, the CLR will try and map it to something .NET has an exception for (OutOfMemoryException, NullReferenceException, etc...). Anything it cannot translate ends up as an SEHException. The only clue you have to go on at that point is the enigmatic HRESULT (the ErrorCode property of the exception). FormatMessage and some elbow grease may help you turn the number into something readable, but otherwise you are at the mercy of the internet:
My particular annoyance today is that when C++ std::vector allocations fail with a std::bad_alloc exception, this is translated to an SEHException exception with HRESULT 0x80004005 = E_FAIL = "Unspecified failure". Completely useless. If I didn't also log the incredibly useful StackTrace property I would not have a clue what was going on.

If you are not using StackTrace, you should be, right now, seriously stop reading this and add it right now, when it saves your job add comments and send money ;-)

No comments: