Infinity or Exception in C# when divide by 0?

CsharpProgrammingServer Side Programming

Divide by zero is the System.DivideByZeroException, which is a class that handles errors generated from dividing a dividend with zero.

Let us see an example.


 Live Demo

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


Exception caught: System.DivideByZeroException: Attempted to divide by zero.
at ErrorHandlingApplication.DivNumbers.division (System.Int32 num1, System.Int32 num2) [0x00000] in <a9b37148b4814c1a849bf4ee94fbe889> :0
Result: 0

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.

Published on 16-Aug-2018 14:48:08