views:

33

answers:

2

What's the correct way of ignoring ThreadAbortException when logging exceptions?

Is it safe to just catch it in an empty catch block to make it disappear?

A: 

It is safe to catch it in a separate catch block. As an alternative you can catch all Exceptions and then check if a given Exception e is ThreadAbortException

I leave this post just because of the comments. Obviously, I was not knowing much about that exception.

ULysses
ThreadAbortExceptions have some unique behavior in the way they interact with try/catch blocks: in some (all?) circumstances, they will automatically be re-thrown from the catch block, so you may not be able to completely "swallow" the exception as you would other types.I admit, I don't fully understand the nuances of this behavior. This thread might be able to give you more insight: http://stackoverflow.com/questions/2830389/whats-the-deal-with-the-hidden-throw-when-catching-a-threadabortexception
mikemanne
It seems I managed to "swallow" the Exception, or at least it's not caught again in the next "catch (Exception)" block that writes a log entry, which is what I wanted to achieve. Just wondering if that's a safe way to do it, and it doesn't break anything else (it all seems to be working fine, but with the mad ASP.NET lifecycle, you never know...)
Farinha
A: 

If you need to stop a ThreadAbortException propogating further up the call stack, you can call Thread.ResetAbort. So try something like:

try
{
  // some code
}
catch (ThreadAbortException ex)
{
  // do some logging
  Thread.ResetAbort();
}

As for "correct" - that depends on your usage scenario. I'd generally be cautious about catching these unless you understand exactly why it has been raised. In escence it is a "stop now, quickly, and drop what you are doing" signal. Resetting it and going on to do further processing should be done with caution.

Rob Levine