当用浮点数除以零时,是否可以强制Java引发错误? [英] Can I force java to throw an error when dividing by zero with floating point numbers?

查看:84
本文介绍了当用浮点数除以零时,是否可以强制Java引发错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个模拟器,该模拟器具有一些碰撞检测代码,并且在检测到碰撞时对每个对象进行了大量的数学运算.

I wrote a simulator that has some collision detection code and does a good bit of math on each object when it detects collisions.

如果这两个对象位于完全相同的位置,或者在极少数其他情况下,我会得到NaN(不是数字)作为它们沿直线某处的位置,我想知道在哪里.通常,如果我对整数执行这些操作,程序将崩溃,但是由于+和-infinity是浮点规范的一部分,因此可以使用.

If these two objects are at the exact same location or in some rare other cases, I'm getting NaN (not a number) as their location somewhere along the line and I'd like to know where. Normally, the program would crash if I did these operations on integers but because + and - infinity are part of the floating point spec, it is allowed.

所以,沿着这条线的某个地方,我取负数的平方根或除以零.

So, somewhere along the line I'm taking a square root of a negative number or dividing by zero.

无论如何,我是否可以使程序在导致此问题的操作上自动崩溃,以便缩小其范围?

Is there anyway I can make my program automatically crash on the operations that cause this so I can narrow it down some?

推荐答案

除非您在除法之前测试数字并自己提出例外,否则我认为您不能提出除以零的例外.

I don't think you can raise a divide by zero exception unless you test the numbers before the division and raise the exception yourself.

浮点数的问题是,标准要求结果必须为NaN(而不是数字)浮点数.而且我所知道的所有JVM和编译器都遵循这方面的标准.

The problem with floats is, that the standard requires that the result gets a NaN (Not a Number) float. And all JVMs and compilers that I am aware off follow the standard in this respect.

这篇关于当用浮点数除以零时,是否可以强制Java引发错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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