How to handle Java ArithmeticException?

  1. You should make sure the divisor isn't zero (0) before attempting any division.
  2. You can handle the ArithmeticException using Java try and catch blocks.

Make sure the divisor isn't zero (0)

When you try the following Java code JVM throws ArithmeticException.
int x=100,y=0; int z= x/y;
Output: Exception in thread "main" java.lang.ArithmeticException: / by zero at Main.main(Main.java:4)
So, you should make sure the divisor isn't zero (0) before attempting any division. This usually means validating the value of the divisor before using it.
public class Main { public static void main(String[] args) { int x=100,y=0; if(y!=0){ int z= x/y; System.out.println("Result : " + z); }else{ System.out.println("undefined (division by zero)"); } } }

Using Java try and catch blocks

The other option to handle Java ArithmeticException is using try and catch blocks. This means that surround the statements that can throw ArithmeticException with try and catch blocks. So, you can Catch the ArithmeticException and take necessary action for your program, as the execution doesn't abort.
public class Main { public static void main(String[] args) { int x=100,y=0; try { int z= x/y; System.out.println("Result : " + z); } catch (ArithmeticException e) { System.out.println("Handle ArithmeticException here..."); } } }

What is Java ArithmeticException?

Arithmetic exceptions are raised during run time by Java Virtual Machine when you try to perform any arithmetic operation which is not possible in mathematics.
how to fix Java ArithmeticException

When an Arithmetic Exception Occurs in Java?

  1. An integer "divide by zero" throws ArithmeticException.
  2. When a big-decimal (non terminating decimal number) is divided by another big-decimal number.