Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Int vs Double and divide by zero exception [duplicate]

We get compile time error when integer is divided by zero whereas in case of double there is no compilation error but at run-time we get infinity/NaN as the result. Any idea why int & double have different behavior when it comes to divide by zero exception?

void Main()
{
    int number = 20;
    var result1 = number/0; // Divide by zero compile time exception

    double doubleNumber = 20;
    var result2 = doubleNumber/0.0; // no compile time error. Result is infinity or NaN
}
like image 844
Pawan Mishra Avatar asked Mar 22 '12 07:03

Pawan Mishra


People also ask

What happens when you divide a double variable by 0?

Dividing a floating-point value by zero doesn't throw an exception; it results in positive infinity, negative infinity, or not a number (NaN), according to the rules of IEEE 754 arithmetic.

What happens when you divide an int variable by 0?

Dividing by zero is an operation that has no meaning in ordinary arithmetic and is, therefore, undefined.

Can a double be divided by an int?

When one of the operands to a division is a double and the other is an int, Java implicitly (i.e. behind your back) casts the int operand to a double. Thus, Java performs the real division 7.0 / 3.0.

Which error will occur when dividing a number with zero?

Microsoft Excel shows the #DIV/0! error when a number is divided by zero (0). It happens when you enter a simple formula like =5/0, or when a formula refers to a cell that has 0 or is blank, as shown in this picture.


2 Answers

Because that's how it's defined. Whereas with integers there are no special values for infinity and NaN, so the compiler throws an error if it can spot the problem at compile time.

like image 155
Dunes Avatar answered Nov 14 '22 22:11

Dunes


theoretically speaking division by zero should result in infinity, but the integer datatype has nothing to represent infinity. the double datatype does, so there is no need to throw an exception there.

like image 34
mtijn Avatar answered Nov 14 '22 22:11

mtijn