I have code to calculate the percentage difference between 2 numbers - (oldNum - newNum) / oldNum * 100;
- where both of the numbers are double
s. 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 int
s would definitely cause an arithmetic division-by-zero exception. Why does Java ignore it when it comes to double
s?
Dividing by zero is an operation that has no meaning in ordinary arithmetic and is, therefore, undefined.
ArithmeticException is the exception which is normally thrown when you divide by 0.
Divide by zero: This Program throw Arithmetic exception because of due any number divide by 0 is undefined in Mathematics.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With