Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Java throw an Exception when dividing by 0.0?

I have code to calculate the percentage difference between 2 numbers - (oldNum - newNum) / oldNum * 100; - where both of the numbers are doubles. I expected to have to add some sort of checking / exception handling in case oldNum is 0. However, when I did a test run with values of 0.0 for both oldNum and newNum, execution continued as if nothing had happened and no error was thrown. Running this code with ints would definitely cause an arithmetic division-by-zero exception. Why does Java ignore it when it comes to doubles?

like image 569
froadie Avatar asked Mar 04 '10 17:03

froadie


People also ask

What happens if you divide by 0 in Java?

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

What exception is thrown when a number is divided by zero in Java?

ArithmeticException is the exception which is normally thrown when you divide by 0.

Is divide by zero checked exception?

Divide by zero: This Program throw Arithmetic exception because of due any number divide by 0 is undefined in Mathematics.

How do you throw a divide by zero exception?

Examples. The following example handles a DivideByZeroException exception in integer division. using System; public class Example { public static void Main() { int number1 = 3000; int number2 = 0; try { Console. WriteLine(number1 / number2); } catch (DivideByZeroException) { Console.


2 Answers

Java's float and double types, like pretty much any other language out there (and pretty much any hardware FP unit), implement the IEEE 754 standard for floating point math, which mandates division by zero to return a special "infinity" value. Throwing an exception would actually violate that standard.

Integer arithmetic (implemented as two's complement representation by Java and most other languages and hardware) is different and has no special infinity or NaN values, thus throwing exceptions is a useful behaviour there.

like image 191
Michael Borgwardt Avatar answered Sep 16 '22 23:09

Michael Borgwardt


The result of division by zero is, mathematically speaking, undefined, which can be expressed with a float/double (as NaN - not a number), it isn't, however, wrong in any fundamental sense.

As an integer must hold a specific numerical value, an error must be thrown on division by zero when dealing with them.

like image 33
Kris Avatar answered Sep 20 '22 23:09

Kris