Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about catching exceptions in Java?

Tags:

java

exception

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?

like image 337
ipkiss Avatar asked Apr 30 '26 19:04

ipkiss


2 Answers

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

like image 137
Kien Truong Avatar answered May 03 '26 08:05

Kien Truong


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.

like image 43
Peter Lawrey Avatar answered May 03 '26 07:05

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!