Search code examples
.netexceptionusingfinally

Determine if code called from an exception handler (using statement)?


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?


Solution

  • 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: Determine if executing in finally block due to exception being thrown