(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?
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 .
Dividing by zero is an operation that has no meaning in ordinary arithmetic and is, therefore, undefined.
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With