Check if a double is infinite in Java
There are two fields for infinity in the Double
class: POSITIVE_INFINITY
and NEGATIVE_INFINITY
which you can check for.
Note that integer division by zero would throw an ArithmeticException
thus your line would have to be 4.0/0
, 4/0.0
or 4.0/0.0
since 4 and 0 are integers and thus result in integer math.
You can use Double.isInfinite(double)
Here's double doc
The above code produces
ArithmeticException: / by zero
You can catch this exception in a try/catch block.