Using finally Blocks

Using finally blocks, you can provide a code that will always execute even if exceptions  are thrown. We learned that if an exception was thrown inside a try block, all the following codes in the try block will be skipped because the execution will immediately jump to the catch block. Those skipped codes could have a vital role in the program. That’s the purpose of the finally block. You place the codes that you think is essential or needs to be executed inside the finally block. The following program shows an example of using a finally block.

using System;
 
namespace FinallyBlockDemo
{
    public class Program
    {
        public static void Main()
        {
            int result;
            int x = 5;
            int y = 0;
 
            try
            {
                result = x / y;
            }
            catch (DivideByZeroException error)
            {
                Console.WriteLine(error.Message);
            }
            finally                                                 
            {                                                       
                Console.WriteLine("finally blocked was reached.");  
            }                                                       
        }
    }
}

Example 1 – Using the finally Block

Attempted to divide by zero.
finally blocked was reached.

The finally block comes right after catch block. If there are multiple catch blocks, the finally block must be placed after them. Note that if you will use a finally block, you are allowed to not define a catch block such as the following:

try
{
    //some code
}
finally
{
    //some code
}

finally blocks are often used when you want to dispose of an object or close a database connection or file stream.

Written by compitionpoint

Leave a Comment

Your email address will not be published. Required fields are marked *