Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why CLR re-throws ThreadAbortException?

I got the following code from book "Concurrent Programming on Windows" :

void Main()
{
    try
    {
        try
        {
            Console.WriteLine("Inside Main Method");
            Thread.CurrentThread.Abort();
        }
        catch(ThreadAbortException)
        {
            Console.WriteLine("Inside First Catch");
            // Trying to swallow but CLR throws it again....
        }
    }
    catch(ThreadAbortException)
    {
        Console.WriteLine("Inside Second Catch");
        //Thread.ResetAbort();
    }
}

I am interested in knowing as why CLR re-throws the ThreadAbortException ? And it keeps doing it until I call "Thread.ResetAbort()". Secondly, is there any other system defined exception, which gets special treatment from CLR ?

like image 265
Pawan Mishra Avatar asked Nov 23 '11 06:11

Pawan Mishra


2 Answers

I am interested in knowing as why CLR re-throws the ThreadAbortException?

Because the thread is being aborted. People handle all exceptions all the time, even though doing so is dangerous. It would be bizarre if an error logging routine, say, kept a thread that was supposed to be destroyed alive forever, no?

is there any other system defined exception, which gets special treatment from CLR?

Yes, there are several. Out of stack and out of memory exceptions, for example, also have special behaviours.

like image 173
Eric Lippert Avatar answered Sep 19 '22 11:09

Eric Lippert


It's a special exception, http://msdn.microsoft.com/en-us/library/system.threading.threadabortexception.aspx, see remarks. From my understanding the reason this happens is that .Net is giving you the ability to do any clean up work before the thread closes.

See this for a bit about the plumbing: http://ondotnet.com/pub/a/dotnet/2003/02/18/threadabort.html

like image 22
Prescott Avatar answered Sep 20 '22 11:09

Prescott