views:

45

answers:

3

I want to do something mildly silly. In my Dispose() method for an object, I want to print a debug trace for the object, telling me all events which happened while it was alive.

But as this takes time and money, I only want to do this if Dispose() is being called because an exception was thrown.

So I would like to do

if (exceptionIsCurrentlyRaised) PrintDebugStuff();

Does .NET have such a exceptionIsCurrentlyRaised property which I can query?

A: 

I don't know if anything like this exists as I have never seen it. But it sounds like you could just create an interface that has a single bool property. Then when you are inside the catch statement but before you call the dispose method just set the flag.

I'm guessing it can't be this easy of a solution but thought I would get some ideas started.

EDIT: Ok I also found this SO article that has a similar problem: http://stackoverflow.com/questions/3301507/determine-if-executing-in-finally-block-due-to-exception-being-thrown

spinon
A: 

Interesting question, but I doubt that this is possible - at least not without some major hacking using debugging or profiling APIs.

Even if you were able to call some debugging API that could give you access to the current exception inside a catch block I don't think you could get the exception inside a finally block (which is where your Dispose method would be executed). By then the exception may have been handled, so, as far as the runtime is concerned, there is no exception.

The only way I can see if doing this is to register to be notified of all exceptions since your object was constructed and from there try to figure out whether the exception was caught or not. This answer may be helpful: http://stackoverflow.com/questions/952304/net-first-chance-exception-listener-for-intensive-debugging/952360#952360

Evgeny
A: 

Actually, this is something like the "IntelliTrace" feature of Visual Studio 2010, which can record what happened during a debugging session when you were not at a breakpoint.

John Saunders
A good obvservation. Is it possible to make use of intellitrace without using VS though?
Tim Lovell-Smith
I really don't know. I haven't gotten into it yet.
John Saunders