#864 – An Example of a finally Block with No catch Block

When an exception occurs while executing code in a try block that has an associated finally block, the code in the finally block will execute before the exception bubbles up the call stack.

Below is an example.  MethodA calls MethodB, which in turn calls MethodC.  MethodC throws an exception.  When this happens, the code in MethodB’s try block is interrupted and the code in the finally block is executed.  The exception then bubbles up the call stack, where it is then caught by the catch block in MethodA.

        private static void MethodA()
        {
            try
            {
                MethodB();
                Console.WriteLine("After MethodB call");
            }
            catch (Exception xx)
            {
                Console.WriteLine("Exception caught in MethodA!");
            }

            Console.WriteLine("Finishing up MethodA");
        }

        private static void MethodB()
        {
            try
            {
                Console.WriteLine("Before MethodC() call");
                MethodC();
                Console.WriteLine("After MethodC() call");
            }
            finally
            {
                Console.WriteLine("MethodB() finally block");
            }

            Console.WriteLine("Finishing up MethodB()");
        }

        private static void MethodC()
        {
            throw new Exception("Uh-oh");
        }

864-001

Advertisements