我应该如何在 Java 中抛出被零除异常而不实际除以零?
我有一个 I2C 设备需要两个输入:分母和分子。两者都写入不同的地址,因此不会进行实际计算(分子/分母
)。这样做的问题是,I2C 设备上可能会发生被零除的情况,因此需要检查被零除错误。理想情况下,如果由 java 代码完成除法,也会发生完全相同的事情。
目前,我已经使用了一个未使用的变量来进行除法,但我担心它会被优化:
public void setKp(int numerator, int divisor)
{
int zeroCheck = numerator / divisor;
//... doesn't use zeroCheck
}
当然有更好的方法!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您不应该抛出 ArithmeticException。由于错误出现在提供的参数中,因此抛出
IllegalArgumentException
。作为文档 说:这正是这里发生的事情。
You should not throw an ArithmeticException. Since the error is in the supplied arguments, throw an
IllegalArgumentException
. As the documentation says:Which is exactly what is going on here.
这样做:
ArithmeticException 是除以 0 时通常抛出的异常。
Do this:
ArithmeticException is the exception which is normally thrown when you divide by 0.
有两种方法可以做到这一点。创建您自己的自定义异常类来表示被零除错误,或者抛出与 Java 运行时在这种情况下抛出的相同类型的异常。
定义自定义异常
然后在您的代码中,您将检查是否被零除并抛出此异常:
Throw ArithmeticException
将检查是否被零除并抛出算术异常添加到您的代码中:
此外,您可以考虑抛出非法参数异常,因为除数为零是传递给 setKp() 方法的错误参数:
There are two ways you could do this. Either create your own custom exception class to represent a divide by zero error or throw the same type of exception the java runtime would throw in this situation.
Define custom exception
Then in your code you would check for a divide by zero and throw this exception:
Throw ArithmeticException
Add to your code the check for a divide by zero and throw an arithmetic exception:
Additionally, you could consider throwing an illegal argument exception since a divisor of zero is an incorrect argument to pass to your setKp() method:
像这样的东西:
Something like: