tags:

views:

582

answers:

3

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

   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;
A: 

This code will throw an ArithmeticException:

int x = 1 / 0;
Joachim Sauer
`System.out.println(1d / 0d);` prints `Infinity`
sfussenegger
-1 And, doesn't throw anything
OscarRyz
My bad: it was integer division that threw the exception.
Joachim Sauer
+2  A: 

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

public static void checkValue(double val) throws ArithmeticException {
    if (Double.isInfinite(val) || Double.isNaN(val))
        throw new ArithmeticException("illegal double value: " + val);
}
sfussenegger
I don't want to call checkValue every time when division by zero or another "bad" operation may occur. I'd like to surround my code with try-catch and check for failures in one code block, having housekeeping stuff (i.e checkValue() calls) out of the main code.
DNNX
@DNNX: the "check in one place" method is supported by `NaN`: When a problem occurs then the end result of your calculation will be `NaN`. Just check for that in the end.
Joachim Sauer
@DNNX "You can't always get what you want / But if you try sometime, you'll find / You get what you need" (Jagger/Richards) ;)
sfussenegger
+5  A: 

It's not possible to make Java throw exceptions for these operations because Java implements the IEEE 754 standard for floating point arithmetic, which mandates that these operations should return specific bit patterns with the meaning "Not a Number" or "Infinity".

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.

Michael Borgwardt
just a note: `Double.NaN != Double.NaN` is **true** and `Double.NaN == Double.NaN` is **false**, better use `Double.isNaN(double)`
Carlos Heuberger
@Interruption: good point
Michael Borgwardt