What is java.lang.ArrayIndexOutOfBoundsException error and how to handle it

java.lang.ArrayIndexOutOfBoundsException

The Java ArrayIndexOutOfBoundsException is a public class that extends the RuntimeExcpetion. The java.lang.ArrayIndexOutOfBoundsException error is thrown in a Java application or applet when you try to use an array element that does not exist.

For example, you have an integer array of 3 elements which index start from 0. This exception will raise if you try to print the fourth element (e.g. intarray[3]).

The demonstration of how this error is raised and how you can handle in the try-catch block is shown below.

Example of error and resolving it

As such, The ArrayIndexOutOfBoundsException error occurs as you try to access an array element that does not exist, this is shown in the example below:

Experience this online


The output will be:

10

20

30

Array element does not exist  :java.lang.ArrayIndexOutOfBoundsException: 3

As you can see, the for loop will print three elements and as the loop reaches the fourth element, that element does not exist and the error is generated which is handled in the try-catch block where we shown a descriptive message.

 

Also see – java exceptions | Error handling in Java

Was this article helpful?

Related Articles

Leave A Comment?