Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the exception not triggered for division by zero here?

Tags:

java

exception

(This is a follow up question to Why is this exception is not printed? Why is it showing an error?)

Here in the below code why is the ArithmeticException not triggered?

class Exp
{
    public static void main(String args[])
    {
        float d,a=1;
        try
        {
            d=0;
            a=44/d; //no exception triggered here.. why?
            System.out.print("It's not gonna print: a="+a); 
        }
        catch(ArithmeticException e)
        {
            System.out.println("Print exception: "+e);
        }
    }
} 

Instead the output is:

It's not gonna print: a=Infinity

What happens?

like image 531
vivek_jonam Avatar asked Aug 26 '12 14:08

vivek_jonam


People also ask

What is the exception if you divide a number by zero?

Any number divided by zero gives the answer “equal to infinity.” Unfortunately, no data structure in the world of programming can store an infinite amount of data. Hence, if any number is divided by zero, we get the arithmetic exception .

What happens if you divide by 0 in Java?

Dividing by zero is an operation that has no meaning in ordinary arithmetic and is, therefore, undefined.

Why is division zero not defined?

Because what happens is that if we can say that zero, 5, or basically any number, then that means that that "c" is not unique. So, in this scenario the first part doesn't work. So, that means that this is going to be undefined. So zero divided by zero is undefined.

Is divide by 0 runtime exception in Java?

Division by zero (integer arithmetic) Since this is a special case of the division operation, Java treats it as an exceptional condition and throws the ArithmeticException exception whenever it encounters it at runtime.


2 Answers

A division by zero throws an exception for integer values, but not for floating values. This is defined in the JLS #15.17.2:

The result of a floating-point division is determined by the rules of IEEE 754 arithmetic:
[...]

  • Division of a nonzero finite value by a zero results in a signed infinity. The sign is determined by the rule stated above.

If you change the type of a and d to int, you will get an exception.

like image 61
assylias Avatar answered Oct 02 '22 16:10

assylias


Because Divide by zero applies to integers and not floats as per JLS

and you would get output as

Its not gonna printed a=Infinity

since this is computed as Infinity

And in case you want to see an exception just change

a=44/d;

to this

a=44/0;
like image 45
Bharat Sinha Avatar answered Oct 02 '22 15:10

Bharat Sinha