Table of Contents

Java Errors and Exception Exercise

Problem Statement-1:

Write a java program using multiple catch blocks. Create a class CatchExercise inside the try block declare an array a[] and initialize with value a[5] =30/5; . In each catch block show Arithmetic exception and ArrayIndexOutOfBoundsException.

Test Data:

a[5] =30/5;

Expected Output :

ArrayIndexOutOfBoundsException occursRest of the code

Solution:

import java.lang.*;
import java.io.*;

public class CatchExercise {
 public static void main(String[] args) {

   try {

     int a[] = new int[5];
     a[5] = 30 / 5;
   } catch (ArithmeticException e) {

     System.out.println("ArithmeticException occurs");
   } catch (ArrayIndexOutOfBoundsException e) {

     System.out.println(" ArrayIndexOutOfBoundsException occurs");
   } catch (Exception e) {
     System.out.println("Parent Exception occurs");
   }
   System.out.println("Rest of the code");
 }
}

/*OUTPUT:
ArrayIndexOutOfBoundsException occurs
Rest of the code  */

Explanation:

In class CatchExercise inside the try block declare an array a[] and initialize with value a[5] =30/5; . In each catch block show Arithmetic exception and ArrayIndexOutOfBoundsException with the exception object e. Hence the array size is 5 and index starts from 0. It does'nt hold the index 5 value so it shows ArrayIndexOutOfBoundsException.

Ask queries
Contact Us on Whatsapp
Hi, How Can We Help You?