How to handle the ArrayStoreException (unchecked) in Java?

JavaObject Oriented ProgrammingProgramming

The java.lang.ArrayStoreException is an unchecked exception and it can occur when we try to store an object of a type in an array of objects of a different type. Usually, one would come across java.lang.ArrayStoreException: java.lang.Integer which occurs when an attempt is made to store an integer in an array of different type like an array of String or array of float, etc.

Example1

Live Demo

public class ArrayStoreExceptionTest {
   public static void main(String[] args) {
      Object[] names = new Float[2];
      names[1] = new Integer(2);
   }
}

Output

Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integer
        at ArrayStoreExceptionTest.main(ArrayStoreExceptionTest.java:4)

In the above program, java.lang.ArrayStoreException: java.lang.Integer occurred 

  • java.lang.ArrayStoreException: Exception thrown by java language when we try to store an object of java.lang.Integer in an array of java.lang.Float.
  • java.lang.Integer: Integer is the type of object that has been tried to store an array of a different type.

How to handle ArrayStoreException

We can handle the ArrayStoreException using try and catch blocks.

  • Surround the statements that can throw ArrayStoreException with try and catch blocks.
  • We can Catch ArrayStoreException.
  • Take necessary action for our program, as we are handling the exception and the execution doesn’t abort.

Example2

Live Demo

public class ArrayStoreExceptionTest {
   public static void main(String[] args) {
      Object[] names = new Float[2];
      try {
         names[1] = new Integer(2);
      } catch (ArrayStoreException e) {
         e.printStackTrace();
         System.out.println("ArrayStoreException is handled");
      }
      System.out.println("Continuing with the statements after try and catch blocks");
   }
}

Output

ArrayStoreException is handled
Continuing with the statements after try and catch blocks
java.lang.ArrayStoreException: java.lang.Integer
      at ArrayStoreExceptionTest.main(ArrayStoreExceptionTest.java:5)


In the above example, when an exception occurs, the execution falls to the catch block from the point of occurrence of an exception. It executes the statement in the catch block and continues with the statement present after the try and catch blocks.

raja
Published on 25-Jun-2019 15:39:55
Advertisements