DivideByZeroException in .NET

In this article we will explain how can we handle the DivideByZeroException in .Net.
  • 1967

Introduction

Exception handling is very common in programs. Exceptions are used to indicate that an error has occurred while running the program. If you divide a number by zero the result will always be infinite. Computers can't handle this situation without using exception handling so its gives an error or exception. This exception is calleDivideByZeroException.

Example

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Dividebyzero

{

    class Program

    {

      static  int N1, N2, N3;

      public static void Ma(int a)

      {

          if (a <= 0)

          {

              // throw an argument zero.

              throw new DivideByZeroException("v2 Cannot Be zero ");

          }

      }

        static void Main(string[] args)

        {

            try

            {

                Console.WriteLine("Enter the number to perform divide operation");

                N1 = Convert.ToInt32(Console.ReadLine());

                Console.WriteLine("Enter the number by which divide operation is to be performed");

                N2 = Convert.ToInt32(Console.ReadLine());

                Ma(N2);

                Console.WriteLine("Result is {0}", N3);

            }

             catch (DivideByZeroException ex)

            {

                Console.WriteLine("Division by Zero occurs" + ex);

                Console.WriteLine("HelpLink = {0}", ex.HelpLink);

                Console.WriteLine("Message = {0}", ex.Message);

                Console.WriteLine("Source = {0}", ex.Source);

                Console.WriteLine("StackTrace = {0}", ex.StackTrace);

                Console.WriteLine("TargetSite = {0}", ex.TargetSite);

            }

            finally

            {

               Console.WriteLine("Task completed");

               Console.ReadLine();

            }

        }

    }

}

The output of following program

Clipboard102.jpg

© 2020 DotNetHeaven. All rights reserved.