#861 – A finally Block Always Executes

When you use a try block, you’re defining a block of code for which you can catch an exception, using a catch block.  You can also include a finally block, which dictates a block of code that will execute whether or not an exception occurs.

Suppose that you have the following code:

                try
                {
                    Console.WriteLine("BEFORE the call");
                    SomeMethod();
                    Console.WriteLine("AFTER the call");
                }
                catch (Exception exc)
                {
                    Console.WriteLine("Exception caught in catch block");
                }
                finally
                {
                    Console.WriteLine("Code in finally block executing");
                }

If an exception does not occur, all of the code in the try block will execute, followed by all of the code in the finally block.

861-001

 

If the SomeMethod method throws an exception, the code in the try block after the call to SomeMethod will not execute.  Instead, the code in the catch block will execute, followed by the code in the finally block.

861-002