开发者

Question about catching exceptions in Java?

开发者 https://www.devze.com 2023-03-04 06:53 出处:网络
I have the following code: public static void main(String[] args) { try { int d1 = 3; int d2 = 0; int d = d1/d2;

I have the following code:

public static void main(String[] args) {
        try {
           int d1 = 3;
           int d2 = 0;
           int d = d1/d2;
        } catch (Exception开发者_开发知识库 ex) {
            System.out.println("Exception");
        } 
    }

When this code is run, it is obvious that exception will occur. However, if I change the code as follows:

public static void main(String[] args) {
        try {
           double d1 = 3;
           double d2 = 0;
           double d = d1/d2;
        } catch (Exception ex) {
            System.out.println("Exception");
        } 
    }

Then the exception does not throw. I really don't get it. Can anyone elaborate on that, please?


Because divide a double by 0.0 will produce NAN or +/- infinity, not an exception.


When you perform integer division by 0 you can get an exception as there is no defined behaviour for this.

There is a defined behaviour for double division in the IEEE standard.


In the second example, no exception occurs because the double data type has special values for positive and negative infinity.

dividing 3d by 0d will result in the special value Double.POSITIVE_INFINITY.


You divided by double instead of int value.If you got exception so you must be divided by int (0) variable.If you divided by float are double you get infinite not exception.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号