1. Overview
ArrayStoreException is thrown at runtime in Java when an attempt is made to store the incorrect type of object in an array of objects. Since ArrayStoreException is an unchecked exception, it isn’t typical to handle or declare it.
In this tutorial, we’ll demonstrate the cause of ArrayStoreException, how to handle it, and best practices for avoiding it.
2. Causes of ArrayStoreException
Java throws an ArrayStoreException when we try to store a different type of object in an array instead of the declared type.
Suppose we instantiated an array with String type and later tried to store Integer in it. In this case, during runtime, ArrayStoreException is thrown:
Object array[] = new String[5];
array[0] = 2;
The exception will be thrown at the second line of code when we try to store an incorrect value type in the array:
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integer
at com.baeldung.array.arraystoreexception.ArrayStoreExceptionExample.main(ArrayStoreExceptionExample.java:9)
Since we declared array as an Object, the compilation is error-free.
3. Handling the ArrayStoreException
The handling of this exception is pretty straightforward. As any other exception, it also needs to be surrounded in a try-catch block for handling:
try{
Object array[] = new String[5];
array[0] = 2;
}
catch (ArrayStoreException e) {
// handle the exception
}
4. Best Practices to Avoid this Exception
It is recommended to declare the array type as a specific class, such as String or Integer, instead of Object. When we declare the array type as Object, then the compiler will not throw any error.
But declaring the array with the base class and then storing objects of a different class will lead to a compilation error. Let’s see this with a quick example:
String array[] = new String[5];
array[0] = 2;
In the above example, we declare the array type as String and try to store an Integer in it. This will lead to a compilation error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from int to String
at com.baeldung.arraystoreexception.ArrayStoreExampleCE.main(ArrayStoreExampleCE.java:8)
It’s better if we catch errors at compile-time rather than runtime as we have more control over the former.
5. Conclusion
In this tutorial, we learned the causes, handling, and prevention of ArrayStoreException in Java.
The complete example is available over on GitHub.
The post Guide to ArrayStoreException first appeared on Baeldung.
Find A Teacher Form:
https://docs.google.com/forms/d/1vREBnX5n262umf4wU5U2pyTwvk9O-JrAgblA-wH9GFQ/viewform?edit_requested=true#responses
Email:
public1989two@gmail.com
www.itsec.hk
www.itsec.vip
www.itseceu.uk
Leave a Reply