#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

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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

  1. Pingback: Dew Drop – June 12, 2013 (#1,566) | Alvin Ashcraft's Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: