1

I have written the code below. And I want the output to be :Error!Division by zero.. But my output is: infinity. What's the problem with this code?

//This is the class:

 public class Exc    
 {
    private double number1;
    private double number2;
    public double result;

    public Exc(double n1,double n2)
    {
        this.number1 = n1;
        this.number2 = n2;
    }

    public void Div(double number1, double number2)
    {

        try
        {
            result = number1 / number2;
            Console.WriteLine(result);
        }

        catch (DivideByZeroException e)
        {
            Console.WriteLine("Error! Division by zero.{0}",e);

        }

    }
}

//This is my program:

static void Main(string[] args)
{

    Console.WriteLine("Enter the first number:");
    double n1 = Convert.ToDouble(Console.ReadLine());
    Console.WriteLine("Enter the second number:");
    double n2 = Convert.ToDouble(Console.ReadLine());

    Exc obj = new Exc(n1, n2);
    obj.Div(n1,n2);

    Console.ReadKey();
}
dcg
  • 4,187
  • 1
  • 18
  • 32
E.Tabaku
  • 116
  • 8
  • 2
    What inputs are you using? – gunr2171 Mar 30 '20 at 14:44
  • Does this answer your question? [Inconsistency in divide-by-zero behavior between different value types](https://stackoverflow.com/questions/4609698/inconsistency-in-divide-by-zero-behavior-between-different-value-types) – xdtTransform Mar 30 '20 at 14:46
  • And https://stackoverflow.com/questions/17473074/0-0-0-0-in-c-sharp-wont-throw-attempted-to-divide-by-zero?noredirect=1&lq=1 – xdtTransform Mar 30 '20 at 14:48

2 Answers2

3

Arithmetic operations with the float and double types never throw an exception. The result of arithmetic operations with those types can be one of special values that represent infinity and not-a-number:

double a = 1.0 / 0.0;
Console.WriteLine(a);                    // output: Infinity
Console.WriteLine(double.IsInfinity(a)); // output: True

Source

Chronicle
  • 1,565
  • 3
  • 22
  • 28
2

You are going to get divide by zero error only in case of integer input in c#. For double the desired output is infinity. You should put a check for Double.IsInfinity if you want to know if it is divided by zero.

Jayram
  • 18,820
  • 6
  • 51
  • 68