为什么Java除以0.0会抛出异常? [英] Why doesn't Java throw an Exception when dividing by 0.0?

查看:986
本文介绍了为什么Java除以0.0会抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有代码来计算两个数字之间的差额 - (oldNum - newNum)/ oldNum * 100; - 其中两个数字都是秒。我希望在oldNum为0的情况下添加一些检查/异常处理。但是,当我对oldNum和newNum进行了值0.0的测试运行时,执行仍然没有发生任何事情,没有发生任何错误。使用 int 运行此代码肯定会导致算术除零异常。为什么当涉及到 double s时,Java会忽略它?

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?

推荐答案

除以零的结果在数学上是未定义的,可以用float / double表示(如 NaN 而不是数字)但是,在任何基本意义上都不是错误的。

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.

这篇关于为什么Java除以0.0会抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆