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

Time:04-04

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.

CodePudding user response:

Double class the following defined

public static final double POSITIVE_INFINITY = 1.0 / 0.0;

public static final double NEGATIVE_INFINITY = -1.0 / 0.0;

In the above code, when the double value returned is printed it matches INFINITY

double result =  comparant.division(zero);
System.out.println( Double.isInfinite(result)); - returns true 
class Entier {
    int A;
    public Entier(int A){
        this.A = A;
    }
    public double division(Entier diviseur){
        return (double) this.A / diviseur.A;
    }
}

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)
        );
        double result =  comparant.division(zero);

        System.out.println( " Is Infinite :"   Double.isInfinite(result) );
        System.out.println( " Is Positive Infinity :"   (Double.POSITIVE_INFINITY == result) );

        System.out.println("1d/0 results in "   1d/0 );
        System.out.println(1/0);

        // 2.4
        //Is Infinite :true
        //Is Positive Infinity :true
        //1d/0 results in Infinity
        // throws ArithmeticException
    }
}

CodePudding user response:

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.

  • Related