What's the deal with the hidden Throw when catching a ThreadAbortException?

Posted by priehl on Stack Overflow See other posts from Stack Overflow or by priehl
Published on 2010-05-13T21:19:12Z Indexed on 2010/05/13 21:24 UTC
Read the original article Hit count: 188

Filed under:
|

I'm going through a book of general c# development, and I've come to the thread abort section.

The book says something along the lines that when you call Thread.Abort() on another thread, that thread will throw a ThreadAbortException, and even if you tried to supress it it would automatically rethrow it, unless you did some bs that's generally frowned upon. Here's the simple example offered.

using System;
using System.Threading;

public class EntryPoint
{
    private static void ThreadFunc()
    {
        ulong counter = 0;
        while (true)
        {
            try
            {
                Console.WriteLine("{0}", counter++);
            }
            catch (ThreadAbortException)
            {
                // Attempt to swallow the exception and continue.
                Console.WriteLine("Abort!");
             }
        }
    }

    static void Main()
    {
        try
        {
            Thread newThread = new Thread(new ThreadStart(EntryPoint.ThreadFunc));
            newThread.Start();
            Thread.Sleep(2000);

            // Abort the thread.
            newThread.Abort();

           // Wait for thread to finish.
           newThread.Join();
        }
       catch (Exception e)
       {
           Console.WriteLine(e.ToString());
       }
    }
}

The book says:

When your thread finishes processing the abort exception, the runtime implicitly rethrows it at the end of your exception handler. It’s the same as if you had rethrown the exception yourself. Therefore, any outer exception handlers or finally blocks will still execute normally. In the example, the call to Join won’t be waiting forever as initially expected.

So i wrapped a try catch around the Thread.Abort() call and set a break point, expecting it to hit this, considering the text says "any outer exception handlers or finally blocks will still execute normally". BUT IT DOES NOT. I'm racking my brain to figure out why.

Anyone have any thoughts on why this isn't the case? Is the book wrong?

Thanks in advance.

© Stack Overflow or respective owner

Related posts about c#

Related posts about threading