Role of finally block during exception handling in C#

In the previous tutorial you learnt about the try and catch blocks and the role they play during exception handling. Let’s revise – If you have a doubt that some code might throw an error then write it inside the try block. Try block is always used with a catch block. If everything goes fine then the code inside catch block will never run. But if some error occurs inside the try block then the code inside the catch block will run.

Finally block

Along with try and catch blocks there is a third block which is used when writing exception handling code. The role of the finally block is very simple – The code inside the finally block will always execute whether an exception occurs or not. Even if there is a return statement inside the try or catch block the finally block will be executed before the return statements sends the control back to the calling function.

Why should you use the finally block?

Suppose you want some code to execute for sure no matter if an exception occurs or not. If you write such code inside the try block then it will not execute if the exception occurs and if you write it inside the catch block then it will not run if no exception occurs. So the best place to write such code is the finally block which will execute for sure in all circumstances.

Finally block is optional

When you write exception handling code you have to use both try and catch blocks. You cannot use a try block without catch. But it’s not compulsory to add the finally block every time you add try-catch blocks. You should use finally block only where you have some important code which you want to execute regardless of the some exception occurring or not.

Example

Look at the code below

static void Main(string[] args)  {      try      {          Console.Write("Enter a number : ");          int i = Convert.ToInt16(Console.ReadLine());            // If input is correct then print this line          Console.WriteLine("
Correct input received...");      }      catch      {          // If input is wrong then print this line          Console.WriteLine("
Catch block : Incorrect input received...");      }      finally      {          // This code will always run          Console.WriteLine("** Finally block executed (always) ");      }  }

Here we have added a finally block to our code. Below are the outputs of this code when an exception occurs and when no exception occurs

Exception handling in C#
 
Output in case an exception occurs

Exception handling in C#
 

Quick Links

E-Magazines

@

Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..

Ok

Login to Open ESchool OR Create your account    Login   SignUp