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:
1 |
<span class="kwrd">public</span> <span class="kwrd">class</span> Util<br />{<br /> <span class="kwrd">static</span> <span class="kwrd">readonly</span> <span class="kwrd">private</span> <span class="kwrd">int</span> _NullReferenceCode;<br /><br /> <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">int</span> NullReferenceCode<br /> {<br /> get { <span class="kwrd">return</span> _NullReferenceCode; }<br /> }<br /><br /> <span class="kwrd">static</span> Util()<br /> {<br /> <span class="rem">//this will store the code for the NullReferenceExcpetion</span><br /> <span class="kwrd">try</span><br /> {<br /> String dum = <span class="kwrd">null</span>;<br /> dum.ToString();<br /> }<br /> <span class="kwrd">catch</span><br /> {<br /> _NullReferenceCode = Marshal.GetExceptionCode();<br /> }<br /> }<br />} |
and then we can use it as follows:
1 |
<span class="kwrd">public</span> <span class="kwrd">void</span> Dispose()<br />{<br /> <span class="kwrd">if</span> (Marshal.GetExceptionCode() == Util.NullReferenceCode)<br /> {<br /> <span class="rem">//do some logic</span><br /> }<br />} |
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).