Try-Catch-Finally in C#


C# exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.

C# exception handling is performed using the following keywords −

  • try − A try block identifies a block of code for which particular exceptions is activated. It is followed by one or more catch blocks.

  • catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.

  • finally − The finally 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 following is an example showing how to handle exceptions in C# −

Example

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

Output

Above, we have set the values in a try, and then caught exceptions in the catch. Finally is also set to show the result −

try {
   result = num1 / num2;
} catch (DivideByZeroException e) {
   Console.WriteLine("Exception caught: {0}", e);
} finally {
   Console.WriteLine("Result: {0}", result);
}

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 20-Jun-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements