Thursday, November 24, 2011

ArrayStoreException


ArrayStoreException is caused when we try to assign an array element of incompatible type. Following is the program that demonstrates it.


packageorg.training.exceptions;

public class ArrayStore {

      public static void main(String[] args) {

            Object array[] = new String[1];
           
            for(int i = 0; i < array.length; i++) {
                 
                  try {
                        // assigning an integer where String is expected
                        array[i] = new Integer(i);
                  }catch(ArrayStoreException ase) {
                        System.err.println("Array Store Exception has been caught, check whether you are passing incompatiable types to your array.");
                        System.err.println("Stack Trace: ");
                        ase.printStackTrace();
                  }
                 
            }
           
            for (Object o : array) {
                  System.out.println(o);
            }
      }

}

Output:
null
Array Store Exception has been caught, check whether you are passing incompatiable types to your array.
Stack Trace:
java.lang.ArrayStoreException: java.lang.Integer
      at org.training.exceptions.ArrayStore.main(ArrayStore.java:12)

No comments:

Post a Comment