Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does it make sense to catch ThreadAbortException and perform no action?

catch (ThreadAbortException)
{ }
catch (Exception ex)
{
    TraceManager.TraceException(ex,
                                (int)ErrorCode.GENERIC_EXCEPTION,
                                ex.StackTrace + "\n" + ex.Message + "\n" + VendorUrl);
}

does it make sense to even have the

catch (ThreadAbortException)
{ }

or will that cause the ThreadAbortException to be swallowed and lost forever?

like image 285
kacalapy Avatar asked Jan 10 '11 21:01

kacalapy


People also ask

Can you catch ThreadAbortException?

ThreadAbortException is a special exception that can be caught, but it will automatically be raised again at the end of the catch block. When this exception is raised, the runtime executes all the finally blocks before ending the thread.

Why thread was being aborted?

If the thread that calls Abort holds a lock that the aborted thread requires, a deadlock can occur. If Abort is called on a thread that has not been started, the thread will abort when Start is called. If Abort is called on a thread that is blocked or is sleeping, the thread is interrupted and then aborted.


1 Answers

ThreadAbortException cannot be caught "completely"; it will automatically be rethrown at the end of the catch block (see the linked MSDN docs page) unless Thread.ResetAbort is called first.

So, the only sensible catch block would be:

catch (ThreadAbortException)
{
    // possibly do something here
    Thread.ResetAbort();
}

But this has a really evil smell. There's probably no reason to do it, so you may want to rethink your approach.

Update: There are many questions on SO that deal with Thread.Abort:

This one has the same answer as I have given here. This one has an answer that expands on "don't ever call Thread.Abort unless Cthulhu is rising" (which I toned down considerably to an "evil smell").

There are also many others.

like image 95
Jon Avatar answered Sep 21 '22 15:09

Jon