如何在Java中抛出零异常,而不用实际除以零? [英] How should I throw a divide by zero exception in Java without actually dividing by zero?

查看:164
本文介绍了如何在Java中抛出零异常,而不用实际除以零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个I2C设备需要两个输入:分母和分子。两者都写入单独的地址,所以没有实际计算(分子/分母)完成。这样做的问题是,在I2C器件上可能会发生零除数,因此需要检查除零错误。理想情况下,如果分割是由java代码完成的,将会发生完全相同的事情。



目前,我已经打了一个未分配的未使用的变量,但是我很担心它会被优化:

  public void setKp(int numerator,int divisor)
{
int zeroCheck =分子/除数;
// ...不使用zeroCheck
}

当然有一个更好的方法!

解决方案

你应该不要抛出一个ArithmeticException。由于错误在提供的参数中,因此抛出一个 IllegalArgumentException 。作为文档说:


抛出表示一种方法已被传递非法或不正确的参数。


这是正是这里发生的。

  if(divisor == 0){
throw new IllegalArgumentException(Argument'divisor'is 0);
}


I have an I2C device that wants two inputs: a denominator and a numerator. Both are written to separate addresses, so no actual calculation (numerator/denominator) is done. The problem with this is that a divide by zero could occur on the I2C device, so a divide by zero error needs to be checked for. Ideally, exactly the same thing would happen if the dividing were done by the java code.

At the moment, I've bodged an unused variable that does the division, but I'm worried it'll get optimized out:

public void setKp(int numerator, int divisor)
{
    int zeroCheck = numerator / divisor;
    //... doesn't use zeroCheck
}

Surely there's a better way!

解决方案

You should not throw an ArithmeticException. Since the error is in the supplied arguments, throw an IllegalArgumentException. As the documentation says:

Thrown to indicate that a method has been passed an illegal or inappropriate argument.

Which is exactly what is going on here.

if (divisor == 0) {
    throw new IllegalArgumentException("Argument 'divisor' is 0");
}

这篇关于如何在Java中抛出零异常,而不用实际除以零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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