Why does this method return double.PositiveInfinity not DivideByZeroException?

2.7k Views Asked by At

I ran the following snippet in the VS2015 C# interactive and got some very weird behavior.

> double divide(double a, double b)
. {
.     try
.     {
.         return a / b;
.     }
.     catch (DivideByZeroException exception)
.     {
.         throw new ArgumentException("Argument b must be non zero.", exception);
.     }
. }    
> divide(3,0)
Infinity    
> 3 / 0
(1,1): error CS0020: Division by constant zero
> var b = 0;
> 3 / b
Attempted to divide by zero.
> 

Why did the method return infinity while 3 / 0 threw an error and 3 / b threw a formated error? Can I force the division to have thrown an error instead of returning infinity?

If I reformat the method to

double divide(double a, double b)
{
    if ( b == 0 )
    {
        throw new ArgumentException("Argument b must be non zero.", new DivideByZeroException());
    }
    return a / b;
}

would the new DivideByZeroException contain all the same information and structure that the caught exception would?

4

There are 4 best solutions below

4
Sergey.quixoticaxis.Ivanov On BEST ANSWER

It's because you use System.Double.

As stated by MSDN DivideByZeroException is thrown only for integral types and Decimal.

That's because it is hard to define "so called" zero for Double value.

PositiveInfinity also results from a division by zero with a positive dividend, and NegativeInfinity results from a division by zero with a negative dividend. (source: MSDN again)

DivideByZeroException is not appropriate for floating point types. Note: You can get NaN though when attempting to divide by zero with a dividend of zero.

0
Christos On

Why did the method return infinity while 3 / 0 threw an error and 3 / b threw a formated error?

Because in the first case the 0 is not an integer, is a double. While in the second is an integer. That you should realize here is that a double is a floating point number. So it doesn't have an exact value like an integer. On the other hand an integer can be represented by a computer with 100% accuracy.

Here you could find a very nice article regarding floating point numbers.

4
codemonger On

Int in Java is 2's complement. A two's-complement integer doesn't have any bits available to store special values like Infinity or NaN, so since the result is not representable in the desired type, an exception has to be thrown. Floating-point numbers do not have this problem (there is a bit pattern available for Infinity), and therefore no exception is needed.

1
Rich Linnell On

As others have stated above, it's due to you using double as the divisor. You can prove it by using your variables example but using double instead of var.

> double a = 3;
> double b = 0;
> a/b
∞