by Dinesh Thakur

Exception handling is a technique of processing problems that occur during the execution of the program. Using exception handling, we can test the code and avoid it from exiting abruptly.

import java.util.Scanner;

public class DivideByZeroException
{
        public static void main(String[] args)
    {
           int x,y;
           //Create scanner object to obtain input from keyboard
           Scanner input=new Scanner(System.in);
            try
           {
               System.out.print("Enter first integer : ");
               x=input.nextInt();  //Read first integer
               System.out.print("Enter second integer : ");
               y=input.nextInt();  //Read second integer
               System.out.println(x + " / " + y +" = " + (x/y));
           }
           catch(ArithmeticException  e)
           {
               System.out.println("Denominator Cannot be Zero while Integer Division");
           }
      }
}

DivideByZeroException Java

The purpose of this program is to display the result of division of two integer numbers and check for division by zero exception. When the user enters the values 10 and 2 for x and y respectively, no exception is thrown and output will be

However; when the user enter the values 8 and 0 for x and y respectively, then the JVM on encountering the statement.

System.out.println(x + "/" + y + "=" + (x/y));

Which contains the arithmetic expression (x/y) will throw an ArithmeticExeption exception. The execution of the code inside the try stops and the attached catch block is examined. Since the type of the exception (i.e. ArithmeticExeption) that occurred matches the type of the catch block parameter, so the statement

System.out.println ("Denominator cannot be zero while integer division");

is executed.