Java Program For Exception Handling

01. Example:

import java.util.*; 

class exceptionHandling {
    
   public static void main(String[] args) {
    
      int x, y, result;
    
      Scanner input = new Scanner(System.in);
      System.out.print("Input two integers: ");
    
      x = input.nextInt();
      y = input.nextInt();
      
      // try block
      try {
         result = x / y;
         System.out.println("Result = " + result);
      }
    
      // catch block
      catch (ArithmeticException e) {
         System.out.println("Exception caught: This Arithmetic Division not possible because we cann't divide by zero.");
      }
      
   }
}

Output:

Input two integers: 12 0
Exception caught: This Arithmetic Division not possible because we cann't divide by zero.

Leave a comment