相关疑难解决方法(0)

为什么用浮点(或双精度)数除零不会在Java中抛出java.lang.ArithmeticException:/ by

以下陈述java.lang.ArithmeticException: / by zero显而易见.

System.out.println(0/0);
Run Code Online (Sandbox Code Playgroud)

因为文字0被认为是int文字并且在整数算术中不允许除以零.

但是,以下情况不会抛出任何异常java.lang.ArithmeticException: / by zero.

int a = 0;
double b = 6.199;
System.out.println((b/a));
Run Code Online (Sandbox Code Playgroud)

它显示Infinity.

以下语句生成NaN(非数字),没有例外.

System.out.println(0D/0); //or 0.0/0, or 0.0/0.0 or 0/0.0 - floating point arithmetic.
Run Code Online (Sandbox Code Playgroud)

在这种情况下,两个操作数都被认为是双精度数.


同样,以下语句不会抛出任何异常.

double div1 = 0D/0; //or 0D/0D
double div2 = 0/0D; //or 0D/0D

System.out.printf("div1 = %s : div2 = %s%n", div1, div2);
System.out.printf("div1 == div2 : %b%n", div1 == div2);
System.out.printf("div1 …
Run Code Online (Sandbox Code Playgroud)

java exception dividebyzeroexception arithmeticexception

57
推荐指数
4
解决办法
4万
查看次数

try-catch为零除

我的问题是关于try-catch块的简单除法示例.你看到第一行尝试?如果我将这两个变量中的任何一个转换为double,则程序无法识别catch块.在我看来,我是否必须执行捕获块.这段代码有什么问题?

public static void main(String[] args) {

    int pay=8,payda=0;  

    try {

        double result=pay/(double)payda; // if I cast any of the two variables, program does not recognize the catch block, why is it so?
        System.out.println(result);
        System.out.println("inside-try");

    } catch (Exception e) {

        System.out.println("division by zero exception");
        System.out.println("inside-catch");

    }
}
Run Code Online (Sandbox Code Playgroud)

java try-catch divide-by-zero

14
推荐指数
3
解决办法
4万
查看次数