How to use Try/catch blocks in C#?

CsharpProgrammingServer Side Programming

Exceptions provide a way to transfer control from one part of a program to another. C# exception handling is built upon four keywords: try, catch, finally, and throw.

  • 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.

The following is an example showing how to use the try, catch, and finally in C#.

Example

 Live Demo

using System;
namespace Demo {
   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

Result: 0
raja
Published on 18-Sep-2018 17:25:19
Advertisements