ArithmeticException handling in java

ArithmeticException class is available in java.lang package and it extends RuntimeException class


public class ArithmeticException extends RuntimeException


ArithmeticException class inherits methods from java.lang.Object class and java.lang.Throwable class.

Hierarchy of ArithmeticException




When ArithmeticException throw

An ArithmeticException throw when an integer number divide by zero which gives an undefined result.
For example, an integer number 10 divides by zero (10/0).

Example:


package com.exceptions;
public class ArithmeticExceptionTest {
       public static void main(String[] args) {
              int i=10/0;
              System.out.println(i);
       }
}


Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero
       at com.exceptions.ArithmeticExceptionTest.main(ArithmeticExceptionTest.java:4)


Handle ArithmeticException with try-catch block


When an ArithmeticException occurs in our program then we can handle the exception with try/catch block.
Place the code in the try block that might throw any exception and catch block is used to handle that exception.  


Example of handling exception



package com.exceptions;
public class ArithmeticExceptionTest {
       public static void main(String[] args) {
              try {
                     int i=10/0;
                     System.out.println(i);
              } catch (ArithmeticException e) {
                     System.out.println("handled in catch "+10/2);
              }
       }
}


Output:


handled in catch 5


The code which is in try block throws an ArithmeticException so that we handled that exception in catch block with an alternative solution.


General example for ArithmeticException


For example, we bought 10 pens with 300 rupees now we want to know the rate for each pen. Generally, we do calculation 300/10 to calculate the rate of each pen but by mistake, we entered 300/0 then it will give the undefined result, this is the one case for ArithmeticException.


Internal code of ArithmeticException from java api  

package java.lang;
public class ArithmeticException
  extends RuntimeException
{
  private static final long serialVersionUID = 2256477558314496007L;
 
  public ArithmeticException() {}
 
  public ArithmeticException(String paramString)
  {
    super(paramString);
  }
}



It has no argument constructor and one String argument constructor.




No comments:

Post a Comment