What is finally statement in C#?


The final block is used 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.

The error handling blocks are implemented using the try, catch, and finally keywords.

Example

You can try to run the following code to implement finally statement −

using System;

namespace ErrorHandlingApplication {
   class DivNumbers {
      int result;

      DivNumbers() {
         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);
         }
      }

      static void Main(string[] args) {
         DivNumbers d = new DivNumbers();
         d.division(25, 0);
         Console.ReadKey();
      }
   }
}

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 20-Jun-2020

218 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements