Java division by zero doesnt throw an ArithmeticException - why?
IEEE 754 defines 1.0 / 0.0
as Infinity and -1.0 / 0.0
as -Infinity and 0.0 / 0.0
as NaN.
By the way, floating point values also have -0.0
and so 1.0/ -0.0
is -Infinity
.
Integer arithmetic doesn't have any of these values and throws an Exception instead.
To check for all possible values (e.g. NaN, 0.0, -0.0) which could produce a non finite number you can do the following.
if (Math.abs(tab[i] = 1 / tab[i]) < Double.POSITIVE_INFINITY)
throw new ArithmeticException("Not finite");
Why can't you just check it yourself and throw an exception if that is what you want.
try {
for (int i = 0; i < tab.length; i++) {
tab[i] = 1.0 / tab[i];
if (tab[i] == Double.POSITIVE_INFINITY ||
tab[i] == Double.NEGATIVE_INFINITY)
throw new ArithmeticException();
}
} catch (ArithmeticException ae) {
System.out.println("ArithmeticException occured!");
}