DivideByZeroExeption in Csharp Programing

40 views Asked by At

I am trying to handle DivideByZeroExeption in C# but the code do not catch the exeption, the Console print result of 10 / d is ∞

            double d = 0;
            try
            {
                double value = 10 / d;
                Console.WriteLine(value);
            }
            catch (DivideByZeroException e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine("Ignore...");
            }

enter image description here But when I changed type of d from double to int or long, this code above works normally.

1

There are 1 answers

0
chandra prakash kabra On BEST ANSWER
 int test = 0;
        try
        {
            double value = 10 / test;
            Console.WriteLine(value);
        }
        catch (DivideByZeroException e)
        {
            Console.WriteLine(e.Message);
            Console.WriteLine("Ignore...");
        }

Now this code will give you the error which you are expecting. It is treating d as something else. DivideByZeroException comes only in case of integer.