How to capture divide by zero exception in Java?


When you divide a number by zero an Arithmetic Exception number is thrown.

Example

Live Demo

public class DividedByZero {
   public static void main(String args[]) {
      int a, b;
      try {
         a = 0;
         b = 54/a;
         System.out.println("hello");
      } catch (ArithmeticException e) {
         System.out.println("you cannot divide a number with zero");
      }
   }
}

Output

you cannot divide a number with zero

Swarali Sree
Swarali Sree

I love thought experiments.

Updated on: 20-Feb-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements