java除零异常是什么,为什么Java除以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?

解决方案

The result of division by zero is, mathematically speaking, undefined, which can be expressed with a float/double (as NaN - not a number), it isnt, 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.

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? 解决方案 The result of division by zero is, mathematically speaking, undefined, which can be expressed with a float/double (as NaN - not a number), it isnt, 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.
经验分享 程序员 微信小程序 职场和发展