Odd behavior: throwing a ThreadAbortException and throwing another exception

As a result of studying this question: Throwing an exception in the Problem does not cause the Task to go into a state with an error , I noticed a very strange behavior with ThreadAbortExceptionwhich I can not understand.

Now I know that ThreadAbortException- this is a special kind of exception to begin with. And the documentation is pretty clear when it says:

ThreadAbortException- This is a special exception that can be caught, but it will be automatically raised again at the end of the block catch.

Scenario # 1 : documentary behavior.

static void Main(string[] args)
{
    try
    {
        Thread.CurrentThread.Abort();
    }
    catch (Exception tae)
    {
        Console.WriteLine("caught exception: " + tae.GetType().Name);
    }
    Console.WriteLine("will never be reached");
}

As expected, it ThreadAbortExceptionautomatically updates, resulting in the following result:

caught exception: ThreadAbortException

# 2. , catch:

static void Main(string[] args)
{
    try
    {
        Thread.CurrentThread.Abort();
    }
    catch (Exception tae)
    {
        Console.WriteLine("caught exception: " + tae.GetType().Name);
        throw new ApplicationException(); // will ThreadAbortException take precedence?
    }
    Console.WriteLine("will never be reached");
}

, , ApplicationException, ThreadAbortException , , . , :

caught exception: ThreadAbortException

Unhandled Exception: System.ApplicationException: Error in the application.
   at ConsoleApplication1.Program.Main(String[] args) in C:\projects\ConsoleApplication1\Program.cs:line 193

ApplicationException ThreadAbortException?!?

β„– 3. , , , try-catch:

static void Main(string[] args)
{
    try
    {
        try
        {
            Thread.CurrentThread.Abort();
        }
        catch (Exception tae)
        {
            Console.WriteLine("caught exception: " + tae.GetType().Name);
            throw new ApplicationException();
        }
    }
    catch (Exception outerEx)
    {
        Console.WriteLine("caught outer exception: " + outerEx.GetType().Name);
    }
    Console.WriteLine("will never be reached");
}

, . catch? ApplicationException? , , will never be reached ?

:

caught exception: ThreadAbortException
caught outer exception: ApplicationException

, catch ApplicationException. catch, ThreadAbortException ?

(). - β„–2 β„–3? β„– 2, , ThreadAbortException, , ? , β„–3, , ThreadAbortException ? ? -?

+4
1

.

Ecma-335 VI E, :

, . , , . ....

( ):

V I. E. 1

. > , , > (, , CLI ).

  • .

(. System.Thread.Abort)

, , , .

. .

- , .

- , .

.

() , .

+1

Source: https://habr.com/ru/post/1599197/


All Articles