如何强制Java抛出算术异常? [英] How to force Java to throw arithmetic exception?

查看:77
本文介绍了如何强制Java抛出算术异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何强制Java在除以0.0或从负双提取根时抛出算术异常?代码如下:

How to force Java to throw arithmetic exception on dividing by 0.0 or extracting root from negative double? Code follows:

   double a = 1; // or a = 0 to test division by 0
   double b = 2;
   double c = 100;

   double d = b*b - 4*a*c;
   double x1 = (-b - Math.sqrt(d)) / 2 / a;
   double x2 = (-b + Math.sqrt(d)) / 2 / a;


推荐答案

这些操作无法使Java抛出异常因为Java实现了针对浮点运算的 IEEE 754 标准,该标准要求这些操作应该返回具有非数字或无限含义的特定位模式。

It's not possible to make Java throw exceptions for these operations because Java implements the IEEE 754 standard for floating point arithmetic, which mandates that these operations should return specific bit patterns with the meaning "Not a Number" or "Infinity".

如果您想特别处理这些情况,可以将结果与相应的常量进行比较 Double.POSITIVE_INFINITY (对于NaN,你必须使用 isNAN() 方法,因为NaN!= NaN)。请注意,您不必在每次单独操作后进行检查,因为后续操作将保持NaN或Infinity值。只需检查最终结果。

If you want to treat these cases specially, you can compare the results with the corresponding constants like Double.POSITIVE_INFINITY (for NaN you have to use the isNAN() method because NaN != NaN). Note that you do not have to check after each individual operation since subsequent operations will keep the NaN or Infinity value. Just check the end result.

这篇关于如何强制Java抛出算术异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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