How to capture divide by zero exception in C#?


System.DivideByZeroException is a class that handles errors generated from dividing a dividend with zero.

Example

Let us see an 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

The values entered here is num1/ num2 −

result = num1 / num2;

Above, if num2 is set to 0, then the DivideByZeroException is caught since we have handled exception above.

Updated on: 20-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements