Friday, July 15, 2011

Does finally block execute everytime?

try catch finally block needs no introduction. Every seasoned programmer would have used it in their code. One misconception harbored by most of my peers is that finally block would always execute irrespective of what happens in try or catch block. I place authors on C# at fault for this as they do not explain the scenario when an exception occurs inside catch block. 

finally block works perfectly when either try blocks executes successfully or an exception occurs inside try block, catch block executes successfully after catching the exception. But what happens if an exception occurs inside catch block?

Try compiling the below listed code and executing it.

using System;

namespace trycatchfinally
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Inside try block.");
                throw new Exception("throw exception");
            }
            catch
            {
                Console.WriteLine("Throwing the exception.");
                throw;
            }
            finally
            {
                Console.WriteLine("Finally block does not execute.");
            }
        }
    }
}

The above listed code is pretty much self explanatory. The point not be missed is that when an exception occurs inside catch block, CLR would search for catch block in stack trace and since there is none, it would result into Unhandled Exception and CLR would unload the appdomain and terminate the process. Since the process got terminated, finally block never got executed.

Moral of the story : Be cautious that code inside catch block should not throw exception.