Finally keyword in C#


The finally keyword is used as a block to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.

Syntax

Following is the syntax −

try {
   // statements causing exception
} catch( ExceptionName e1 ) {
   // error handling code
} catch( ExceptionName e2 ) {
   // error handling code
} catch( ExceptionName eN ) {
   // error handling code
} finally {
   // statements to be executed
}

Example

Let us see an example to implement the finally block −

 Live Demo

using System;
public class Demo {
   int result;
   Demo() {
      result = 0;
   }
   public void division(int num1, int num2) {
      try {
         result = num1 / num2;
      } catch (DivideByZeroException e) {
         Console.WriteLine("Exception caught = {0}", e);
      } finally {
         Console.WriteLine("Result = {0}", result);
      }
   }
   public static void Main(string[] args) {
      Demo d = new Demo();
      d.division(100, 0);
   }
}

Output

This will produce the following output −

Exception caught = System.DivideByZeroException: Attempted to divide by zero.
   at Demo.division(Int32 num1, Int32 num2) in d:\Windows\Temp
0kebv45.0.cs:line 11 Result = 0

Updated on: 11-Dec-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements