Search code examples
javaarithmeticexception

Division by zero doesn't always throw java.lang.ArithmeticException


Why does it show Infinity instead of throwing the exception?

Integer Class :

public class Entier {
    int A;
    public Entier(int A){
        this.A = A;
    }
    public double division(Entier diviseur){
        return (double) this.A / diviseur.A;
    }
}

TestDivision Class

public class TestDivision {
    public static void main(String[] args) {

        Entier compare = new Entier(5);
        Entier comparant = new Entier(12);
        Entier zero = new Entier(0);
        System.out.println(
                comparant.division(compare)
        );
        System.out.println(
                comparant.division(zero)
        );
        System.out.println(1/0);
        // 2.4
        // Infinity
        // throws ArithmeticException
    }
}

I'm using Amazon Corretto JDK-17.


Solution

  • To understand the difference between your two cases, note that

    (double) this.A / diviseur.A
    

    is equivalent to

    ((double)this.A) / diviseur.A
    

    since casting takes precedence over division.

    So although A is an int you are doing a floating-point division that allows division by zero with a result of plus/minus infinity.

    To the contrary 1/0 is a pure integer-division that should give an integer-result, so infinity would not be valid and the ArithmeticException is thrown.