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:

public class Util
{
static readonly private int _NullReferenceCode;

public static int NullReferenceCode
{
get { return _NullReferenceCode; }
}

static Util()
{
//this will store the code for the NullReferenceExcpetion
try
{
String dum = null;
dum.ToString();
}
catch
{
_NullReferenceCode = Marshal.GetExceptionCode();
}
}
}

and then we can use it as follows:

public void Dispose()
{
if (Marshal.GetExceptionCode() == Util.NullReferenceCode)
{
//do some logic
}
}

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).

TOP