java.lang.ArrayIndexOutOfBoundsException is a runtime exception, so it’s a unchecked exception and don’t need to be thrown explicitly from method. Refer Exception Handling in java


  • ArrayIndexOutOfBoundsException is thrown to indicate that we are trying to access array element with an illegal index.
  • This exception is thrown when the index is either negative or greater than or equal to the size of the array.

ArrayIndexOutOfBoundsException Class Diagram

ArrayIndexOutOfBoundsException super classes are Exception, RuntimeException and IndexOutOfBoundsException.


java.lang.ArrayIndexOutOfBoundsException Example

Let’s look at a simple example where our program may throw ArrayIndexOutOfBoundsException based on user input.

Below log shows one of the execution of above program.

So our program can throw ArrayIndexOutOfBoundsException because of illegal input from user. Also notice that exception stack trace prints the illegal index causing the exception.

How to fix ArrayIndexOutOfBoundsException

We shouldn’t try to recover from this exception, we should try to mitigate it by checking if the index value passed is a valid value or not. Also note that this situation can occur mostly in case of user input, if we are creating array ourself and iterating over it’s elements then chances of this exception are less.

Below code snippet shows the small change in program while taking user input to access the element, if value passed is invalid then a warning message is shown to pass the valid value.

Now the output will be like below when illegal index is passed.

So this is how we avoid getting ArrayIndexOutOfBoundsException in our program. That’s all for a quick roundup on java.lang.ArrayIndexOutOfBoundsException.

Reference: API Doc

By admin

Leave a Reply

%d bloggers like this: