如何强制Java抛出算术异常?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2281275/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:37:58  来源:igfitidea点击:

How to force Java to throw arithmetic exception?

javaexception

提问by DNNX

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

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

   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;

采纳答案by Michael Borgwardt

It's not possible to make Java throw exceptions for these operations. Java implements the IEEE 754standard for floating point arithmetic, which mandates that these operations should return specific bit patterns with the meaning "Not a Number" or "Infinity". Unfortunately, Java does notimplement the user-accessible status flags or trap handlers that the standard describes for invalid operations.

不可能让 Java 为这些操作抛出异常。Java 实现了IEEE 754浮点算术标准,该标准要求这些操作应返回具有“非数字”或“无穷大”含义的特定位模式。不幸的是,Java没有实现标准为无效操作描述的用户可访问状态标志或陷阱处理程序。

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.

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

回答by Joachim Sauer

This code will throw an ArithmeticException:

此代码将抛出ArithmeticException

int x = 1 / 0;

回答by sfussenegger

I think, you'll have to check manually, e.g.

我认为,您必须手动检查,例如

public double void checkValue(double val) throws ArithmeticException {
    if (Double.isInfinite(val) || Double.isNaN(val))
        throw new ArithmeticException("illegal double value: " + val);
    else
        return val;
}

So for your example

所以对于你的例子

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