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 };
Array.Copy(arrayOne, arrayTwo, -1);
catch (ArgumentOutOfRangeException ex)
Console.WriteLine("Error Occured:: "+ ex);
Console.WriteLine("\n\nThis statement is always executed. Because its written in finally block.");
Code Description: -

1.       Using System (include the System namespace).
2.       Create MindsctickArgumentOutOfRangeExample class.
4.       Create Main method.
6.       Create int[] type array with arrayOne named
7.       Create int[] type array with arrayTwo named
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: -

  Modified On Sep-18-2014 01:24:14 PM

Leave Comment