Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java division by zero doesnt throw an ArithmeticException - why?

Why doesn't this code throw an ArithmeticException? Take a look:

public class NewClass {

    public static void main(String[] args) {
        // TODO code application logic here
        double tab[] = {1.2, 3.4, 0.0, 5.6};

        try {
            for (int i = 0; i < tab.length; i++) {
                tab[i] = 1.0 / tab[i];
            }
        } catch (ArithmeticException ae) {
            System.out.println("ArithmeticException occured!");
        }
    }
}

I have no idea!

like image 709
Katie Avatar asked Jan 03 '13 11:01

Katie


4 Answers

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");
like image 109
Peter Lawrey Avatar answered Oct 15 '22 07:10

Peter Lawrey


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!");
    }
like image 39
Waqas Ilyas Avatar answered Oct 15 '22 07:10

Waqas Ilyas


That's because you are dealing with floating point numbers. Division by zero returns Infinity, which is similar to NaN (not a number).

If you want to prevent this, you have to test tab[i] before using it. Then you can throw your own exception, if you really need it.

like image 25
gd1 Avatar answered Oct 15 '22 07:10

gd1


0.0 is a double literal and this is not considered as absolute zero! No exception because it is considered that the double variable large enough to hold the values representing near infinity!

like image 12
codeMan Avatar answered Oct 15 '22 08:10

codeMan