blog

Home / DeveloperSection / Blogs / Use Finally Blocks in C#

Use Finally Blocks in C#

Vijay Shukla3477 17-Jun-2013

In this blog I am trying to explain the concept of Finally Blocks in C#

Finally Block

A finally block is always executed, regardless of whether an exception is thrown. Finally provides a construct for ensuring the correct execution of programs. It ensures a block of statements are always reached before the enclosing method is exited.

Working of Finally Block

When an exception occurs, execution stops and control is given to the closest exception handler. This often means that lines of code you expect to always be called are not executed. Some resource cleanup, such as closing a file, must always be executed even if an exception is thrown. To accomplish this, you can use a finally block.

Example: -

 using System;
class MindsctickArgumentOutOfRangeExample
{
public static void Main()
{
int[] arrayOne = { 0, 0 };
int[] arrayTwo = { 0, 0 };
try
{
Array.Copy(arrayOne, arrayTwo, -1);
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine("Error Occured:: "+ ex);
}
finally
{
Console.WriteLine("\n\nThis statement is always executed. Because its written in finally block.");
}
Console.ReadKey();
}
}
Code Description: -

1.       Using System (include the System namespace).
2.       Create MindsctickArgumentOutOfRangeExample class.
4.       Create Main method.
6.       Create int[] type arraywitharrayOnenamed
7.       Create int[] type arraywitharrayTwonamed
8.       Start try block.
10.   In this line trying to copy array source array to destination array.
12.   Start catch block.
14.   Statement for catch block.
16.   Start finally block.
18.   Statement for finally block.

Output: -

Use Finally Blocks in C#

Updated 18-Sep-2014

Leave Comment

Comments

Liked By