An exception is thrown into the trap and finally. CLR behavior against try-catch block

I wrote a simple C # console application:

class Mystery
{
    static void Main(string[] args)
    {
        MakeMess();
    }

    private static void MakeMess()
    {
        try
        {
            System.Console.WriteLine("try");
            throw new Exception(); // let invoke catch
        }
        catch(Exception)
        {
            System.Console.WriteLine("catch");
            throw new Exception("A");
        }
        finally
        {
            System.Console.WriteLine("finally");
            throw new Exception("B");
        }
    }
}

The output indicated in the console:

to try

catch

Unhandled exception: System.Exception: A in Mystery.Program.MakeMess () in ...

It seems that the CLR caught A , and the finally block was not called at all.

But when I surround the MakeMess () call with a try-catch block:

static void Main(string[] args)
{
    try
    {
        MakeMess();
    }
    catch(Exception ex)
    {
        System.Console.WriteLine("Main caught " + ex.Message);
    }
}

The output looks completely different:

to try

catch

finally,

The main caught B

It seems that the exception propagating from MakeMess () is different when the Exception is strictly handled outside the method.

What is the explanation for this behavior?

+4
source share
2 answers

, , finally . , , , , finally :

MSDN :

, finally . , , finally , . , , , . . CLR.

, , , finally, . , finally, , catch try-finally. , , try try-finally . , , try-finally, , , . , finally , .

finally , , : .

+2

, finally ?:

# 4 ยง 8.9.5: finally , .

, , , .

-1

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


All Articles