try-catch为零除 [英] try-catch for division by zero

查看:141
本文介绍了try-catch为零除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My question is about try-catch blocks on a simple division by zero example. You see the first line of try? If I cast any of those two variables to the double the program does not recognize the catch block. In my opinion, whether I cast or not only the catch block must be executed. What is wrong on this code?

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");

    }
}


推荐答案

除以零对浮点数有效。


  • 1/0产生无穷大。

  • ( - 1)/ 0产生-Infinity。

  • 0/0产生NaN。

这些数字在IEEE 754中正确定义。

These "numbers" are properly defined in IEEE 754.

另一方面,整数除以零会抛出,因为无法将无穷大表示为 int

Integer division by zero, on the other hand, throws because one cannot represent infinity as an int.

这篇关于try-catch为零除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆