ipkiss
ipkiss

Reputation: 13651

Question about catching exceptions in Java?

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?

Upvotes: 2

Views: 120

Answers (4)

user2999267
user2999267

Reputation: 1

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.

Upvotes: 0

Stephan
Stephan

Reputation: 4443

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.

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533442

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.

Upvotes: 2

Kien Truong
Kien Truong

Reputation: 11383

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

Upvotes: 8

Related Questions