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

Use Finally Blocks in C#


C# C# 
Ratings:
0 Comment(s)
 1597  View(s)
Rate this:

Use Finally Blocks in C#

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: -

1.  using System;

2.  class MindsctickArgumentOutOfRangeExample

3.  {

4.  public static void Main()

5.  {

6.  int[] arrayOne = { 0, 0 };

7.  int[] arrayTwo = { 0, 0 };

8.  try

9.  {

10. Array.Copy(arrayOne, arrayTwo, -1);

11. }

12. catch (ArgumentOutOfRangeException ex)

13. {

14. Console.WriteLine("Error Occured:: "+ ex);

15. }

16. finally

17. {

18. Console.WriteLine("\n\nThis statement is always executed. Because its written in finally block.");

19. }

20. Console.ReadKey();

21. }

22. }

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: -


Don't want to miss updates? Please click the below button!

Follow MindStick