How to handle the ArithmeticException (unchecked) in Java?


The java.lang.ArithmeticException is an unchecked exception in Java. Usually, one would come across java.lang.ArithmeticException: / by zero which occurs when an attempt is made to divide two numbers and the number in the denominator is zero. ArithmeticException objects may be constructed by the JVM.

Example1

Live Demo

public class ArithmeticExceptionTest {
   public static void main(String[] args) {
      int a = 0, b = 10;
      int c = b/a;
      System.out.println("Value of c is : "+ c);
   }
}

In the above example,  ArithmeticExeption is occurred due to denominator value is zero.

  • java.lang.ArithmeticException: Exception thrown by java during division.
  • / by zero: is the detail message given to ArithmeticException class while creating the ArithmeticException object.

Output

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


How to handle ArithmeticException

Let us handle the ArithmeticException using try and catch blocks.

  • Surround the statements that can throw ArithmeticException with try and catch blocks.
  • We can Catch the ArithmeticException
  • Take necessary action for our program, as the execution doesn’t abort.

Example2

Live Demo

public class ArithmeticExceptionTest {
   public static void main(String[] args) {
      int a = 0, b = 10 ;
      int c = 0;
      try {
         c = b/a;
      } catch (ArithmeticException e) {
         e.printStackTrace();
         System.out.println("We are just printing the stack trace.\n"+ "ArithmeticException is handled. But take care of the variable \"c\"");
      }
      System.out.println("Value of c :"+ c);
   }
}

When an exception occurs, the execution falls to the catch block from the point of occurrence of an exception. It executes the statement in the catch block and continues with the statement present after the try and catch blocks.

Output

We are just printing the stack trace.
ArithmeticException is handled. But take care of the variable "c"
Value of c is : 0
java.lang.ArithmeticException: / by zero
        at ArithmeticExceptionTest.main(ArithmeticExceptionTest.java:6)

Updated on: 30-Jul-2019

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements