More on Using Marshal.GetExceptionCode()

A long time ago Ayende pointed out that GetExcpetionCode can be used to know whether an exception was thrown from inside a finally clause. We have found this technique also useful (thank you Ayende) from inside a Dispose method.

However, we also needed to know the exception type that was thrown and this apparently is not easily done. Up until now we have not found a “proper” mechanism, so we had to revert to some messy workaround. This works for us, only due to the fact that the only interesting exception type we needed to recognize is the NullReferanceException.

here is how to do it:

and then we can use it as follows:

Up until now we have not found a good API to translate the code returned to a usable exception object (or any other alternative), which is kind of frustrating since we do know that info is out there (specifically its on the IL stack) and we also know that it can be accessed using the $exception in the quick watch window (BTW the $exception thing by itself is a very handy trick).