Search code examples
c#exception

C# exception handling finally block before catch block


I am quite confused with how exceptions are getting thrown in C#. If an exception occurs, in the try block, 1.it gets thrown to the catch block, 2. If and only if the catch block catches it the finally block will be executed. 3. The finally block gets executed last, provided the catch statement caught it.

However, when I try to run the program below, the output is A,B not BA.Is there something wrong with my understanding? Thank you.

class Program
 {
     public static void Main(string[] args)
     {
         try
         {
             int a = 2;
             int b = 10 / a;
             try
             {
                 if (a == 1)
                     a = a / a - a;
                 if (a == 2)
                 {
                     int[] c = { 1 };
                     c[8] = 9;
                 }
             }
             finally
             {
                 Console.WriteLine("A");
             }
        }
        catch (IndexOutOfRangeException e)
        {
             Console.WriteLine("B");
        }
        Console.ReadLine();
    }
 }

The exception occurs in a==2, and I know the outer catch will catch this exception. However, the finally is being executed first? Any reason as to why this is showing?

edited

From C# docs we know Finally block gets executed whether or not an exception has occured.

However, my finally block never gets executed and in return I am getting a run time error

class Program
{
    public static void Main(string[] args)
    {
        try
        {
            int a = 2;
            int b = 10 / a;
            try
            {
                if (a == 1)
                    a = a / a - a;
                if (a == 2)
                {
                    int[] c = { 1 };
                    c[8] = 9;
                }
            }
            finally
            {
                Console.WriteLine("A");
            }
        }

        finally{
            Console.WriteLine("finally");
        }
        
        Console.ReadLine();
    }
}

Solution

  • In your first code, the reason that the finally (A) runs before the catch (B) is because when the exception is thrown, you exit the inner block (causing the finally to run) before the outer block's catch comes into play. Consider this code:

    private void TestTryCatchFinally()
    {
        try
        {
            Debug.WriteLine("Start Outer Try");
            try
            {
                Debug.WriteLine("Start Inner Try");
                throw new Exception("Exception from inner try");
                Debug.WriteLine("End of Inner Try - never reaced");
            }
            //remove this catch block for second test
            catch (Exception)
            {
                Debug.WriteLine("In inner catch");
            }
            //end of code to remove
            finally
            {
                Debug.WriteLine("In Inner Finally");
            }
        }
        catch (Exception)
        {
            Debug.WriteLine("In outer catch");
        }
        finally
        {
            Debug.WriteLine("In outer finally");
        }
    }
    

    If I run this code, I get this output:

    Start Outer Try
    Start Inner Try
    Exception thrown: 'System.Exception' in MyTestApp.exe
    In inner catch
    In Inner Finally
    In outer finally
    

    Which is what you expect. But, if I remove the inner catch block (as noted in the code), I get this output:

    Start Outer Try
    Start Inner Try
    Exception thrown: 'System.Exception' in MyTestApp.exe
    In Inner Finally
    In outer catch
    In outer finally
    

    In this case, as soon as execution exits the inner try block, the finally code executes. Then the outer catch block has it's turn.