When dividing by zero does not throw ArithmeticException in java


What is hierarchy of java.lang.ArithmeticException?

-java.lang.Object
-java.lang.Throwable
 -java.lang.Exception
  -java.lang.RuntimeException
   -java.lang.ArithmeticException


When dividing by zero does not throw ArithmeticException in java ?
The IEEE defines some standards for floating point divisions.

When 1.0/0.0 is done, java uses floating point division standards. (1.0 and 1.0 are literal of double type)


1.0/0.0 returns Infinity
-1.0/0.0 returns -Infinity
0.0/0.0 returns NaN (NaN stands for Not-a-Number)

Program to perform 1.0/0.0, -1.0/0.0 and 0.0/0.0 >
public class DivideByZeroDoesntThrowArithmeticException2 {
public static void main(String[] args) {
     try {
          System.out.println(1.0/0.0); //Infinity
          System.out.println(-1.0/0.0); //-Infinity
          System.out.println(0.0/0.0); //NaN
     } catch (ArithmeticException e) {
          e.printStackTrace();
     }
}
}
/*OUTPUT
Infinity
-Infinity
NaN
*/


Program > How to generate ArithmeticException when 1.0/0.0  is done.
public class DivideByZeroInfinity {
public static void main(String[] args) {
     try {         
          if (1.0/0.0 == Double.POSITIVE_INFINITY)
            throw new ArithmeticException("Infinity");
     } catch (ArithmeticException e) {
          e.printStackTrace();
     }
}
}
/*OUTPUT
java.lang.ArithmeticException: Infinity
at DivideByZeroInfinity.main(DivideByZeroInfinity.java:5)
*/


Program > How to generate ArithmeticException when -1.0/0.0  is done.
public class DivideByZeroNegativeInfinity {
public static void main(String[] args) {
     try {
          if (-1.0/0.0 == Double.NEGATIVE_INFINITY)
            throw new ArithmeticException("-Infinity");
    
     } catch (ArithmeticException e) {
          e.printStackTrace();
     }
}
}
/*OUTPUT
java.lang.ArithmeticException: -Infinity
at DivideByZeroNegativeInfinity.main(DivideByZeroNegativeInfinity.java:5)
*/

Must read for you :

No comments:

Post a Comment