Katie Katie - 3 years ago 162
Java Question

Java division by zero doesnt throw an ArithmeticException - why?

Why this code doesn't 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!

Answer Source

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!");
    }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download