Is there an equivalent construct within managed .NET (or C#-specific) code to the ICorDebugThread::GetCurrentException
method, or the $exception
helper that you can use in a watch window / within MSDEV.
It would effectively give an Exception
object for the current thread. An example use would be to detect if a method has been called from within a catch
block for a particular type of Exception
. I quickly realised of course that the correct thing to do would be pass this information to said method explicitly, however I remain curious: has anyone come across this?
If case you haven't seen $exception
, etc, before, please see here:
http://blogs.msdn.com/b/jmstall/archive/2006/02/03/get-current-exception.aspx
Edit: I remember the original idea/reason now: though it is a dead-end. I was thinking of reducing exception catch-all/rethrow code to something smaller than the 6 lines for 'try
, {
, }
, catch
, {
, }
'. I figured I could use a using
statement, with some helper object, like this:
using (new RethrowExceptionHelper<MyException>())
{
// if exception thrown here, it would auto-throw a catch-all MyException
}
I figured that since the Dispose
of RethrowExceptionHelper
would be called in a finally
block, there's a chance that there might be some context of the Exception that was thrown... but of course there won't be, because it's roughly-speaking a finally
, not a catch
. Again, I realise even if this did work it's not ideal code, and using try
/catch
would be may more explicit. But still I remain curious :)
I'm guessing also that a valid solution would be to use some extension or delegate, like the example below, but refactored so it doesn't create an Exception
instance each time..
new MyException().ThrowIfFails(() =>
{
// if exception thrown here, extension method on Exception class would throw itself
});