Search code examples
javaarithmeticexception

Java division by zero doesn't 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!");
        }
    }
}

Solution

  • 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 (!Double.isFinite(tab[i]))
                    throw new ArithmeticException();
            }
        } catch (ArithmeticException ae) {
            System.out.println("ArithmeticException occured!");
        }