除以零并不总是抛出 java.lang.ArithmeticException

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

为什么显示 Infinity 而不是抛出异常?

整数 Class :

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

测试部门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
    }
}

我正在使用亚马逊 Corretto JDK-17。

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;

在上面的代码中,当打印返回的双精度值时,它匹配 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
    }
}

要了解您的两种情况之间的区别,请注意

(double) this.A / diviseur.A

相当于

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

因为转换优先于除法。

因此,虽然 A 是一个 int,但您正在做一个 floating-point 除法,它允许除以零,结果是 plus/minus 无穷大。

相反,1/0 是一个纯 integer-division,应该给出一个 integer-result,因此无穷大将无效并抛出 ArithmeticException