Ошибка ArrayIndexOutOfBoundsException Java
ArrayIndexOutOfBoundsException – это исключение, появляющееся во время выполнения. Оно возникает тогда, когда мы пытаемся обратиться к элементу массива по отрицательному или превышающему размер массива индексу. Давайте посмотрим на примеры, когда получается ArrayIndexOutOfBoundsException в программе на Java.

Попробуйте выполнить такой код:
Вы увидите ошибку:
Что здесь произошло? Ошибка в строке 27 – мы вызвали метод deposit(), а в нем уже, в строке 22 – попытались внести в поле массива значение «deposit». Почему выкинуло исключение? Дело в том, что мы инициализировали массив размера 11 (number = 11), н опопытались обратиться к 12-му элементу. Нумерация элементов массива начинается с нуля. Так что здесь надо сделать, например, так
Но вообще, это плохой код, так писать не надо. Давайте рассмотрим еще один пример возникновения ошибки ArrayIndexOutOfBoundsException:
Здесь массив заполняется случайными значениями. При выполнении IntelliJ IDEA выдаст ошибку
В строке 37 мы заносим значение в массив. Ошибка возникла помтому, что индекса 10 нет в массиве arr, поэтому условие цикла i <= arr.length надо поменять на i < arr.length
Конструкция try для ArrayIndexOutOfBoundsException
ArrayIndexOutOfBoundsException можно обработать с помощью конструкции try-catch. Для этого оберните try то место, где происходит обращение к элементу массива по индексу, например, заносится значение. Как-то так:
Но я бы рекомендовал вам все же не допускать данной ошибки, писать код таким образом, чтобы не пришлось ловить исключение ArrayIndexOutOfBoundsException.

Автор этого материала — я — Пахолков Юрий. Я оказываю услуги по написанию программ на языках Java, C++, C# (а также консультирую по ним) и созданию сайтов. Работаю с сайтами на CMS OpenCart, WordPress, ModX и самописными. Кроме этого, работаю напрямую с JavaScript, PHP, CSS, HTML — то есть могу доработать ваш сайт или помочь с веб-программированием. Пишите сюда.
заметки, ArrayIndexOutOfBoundsException, java, ошибки, исключения
What is ArrayIndexOutOfBoundsException?
In Java, ArrayIndexOutOfBoundsException is an exception that occurs when we try to access an array element at an index that is outside the bounds of the array. This means that the index being accessed is either negative or greater than or equal to the size of the array. Let's discuss it in detail.
Before discussing more about array index out of exception in java, let's see what is index in an array. Index ( plural: Indices ) is nothing but the position of a memory block from the starting position of the array, the thing to note here is that the index starts from 0 instead of 1 . For example, if the size of an arbitrary array is n n n , then all its index lies in the range [ 0 , n − 1 ] [0, n-1] [ 0 , n − 1 ] . Where the 0 t h 0^
Now let's again come back to array index out of bound exception, as the name out of bound suggests, whenever we try to access an array element whose index is out of bound of the array (not in the range) index we get the array index out of bound exception at the runtime.
For example,
Example of Array Index Out of Bound Exception
Array index out of bounds exception can only be found at the runtime (when the program gets executed). Therefore, whenever we try to access the index out of the array bounds, the ArrayIndexOutOfBoundsException exception is thrown at the runtime, and the execution of the program gets terminated.
Let's see how-
Output:
Now let's see how the List data structure reacts when we try to access an invalid element.
Output:
Note: Note that using list also fetched the error, because internally ArrayList is implemented using the array data structure.
How to Handle Array Index Out of Bound Exception?
Why there is a need to handle this exception? Let's say you are playing an open world game, and you are trying to go beyond the map of the game. Generally, while doing these things we get a notice that "This place does not exist" or "You are not permitted to go there" which is because the developer of the game handled the case of a player going outside the map bound. If the developer hadn't handled this exception it would have resulted in the crashing of your game (which you will never want ). Therefore, it is very much necessary to handle all the exceptions while building software.
To handle this exception, we have two ways —
Using For-each Loop (intutive way)
Here is the example that shows how to handle array index out of bound exception in java using for-each loop —
Output:
Note: Note that for-each loop can also be used on the arrays of other data types and even with other data structures like ArrayList, Queue, LinkedList, etc.
Using Try Catch
In exception handling in java, we have seen how we can use the try-catch statements to catch exceptions without terminating the program. Let's have a quick revision here, initially the statements written in the try block starts executing and whenever an exception is caught the program directly starts executing the statements written in the catch block.
Therefore, whenever we try to access an invalid index the catch block will get executed and the corresponding error message can be printed to the console or/and exception can be thrown for easier debugging.
Here is the example that shows how to handle array index out of bound exception in java using try-catch —
Output:
As you can see, firstly all the statements in the try block are executed until an exception is caught. And as soon as any exception is caught, statements written inside the catch block get executed. Finally, the remaining program (written outside the try-catch block) gets executed.
[Solved] ArrayIndexOutOfBoundException in JAVA

java.lang.ArrayindexOutOfboundsException is Runtime and Unchecked Exception. It’s subclass of java.lang IndexOutOfBoundsException.
ArrayIndexOutOfBoundsException is most common error in Java Program. It throws when an array has been accessed with an illegal index either negative or greater than or equal to the size of the array.
Arrayindexoutofbounds exception java что за ошибка

Java supports the creation and manipulation of arrays as a data structure. The index of an array is an integer value that has value in the interval [0, n-1], where n is the size of the array. If a request for a negative or an index greater than or equal to the size of the array is made, then the JAVA throws an ArrayIndexOutOfBounds Exception. This is unlike C/C++, where no index of the bound check is done.
The ArrayIndexOutOfBoundsException is a Runtime Exception thrown only at runtime. The Java Compiler does not check for this error during the compilation of a program.
Expected Output:
Original Output:
Runtime error throws an Exception:
Here if you carefully see, the array is of size 5. Therefore while accessing its element using for loop, the maximum index value can be 4, but in our program, it is going till 5 and thus the exception.
Let’s see another example using ArrayList:
Runtime error here is a bit more informative than the previous time-
Let us understand it in a bit of detail:
- Index here defines the index we are trying to access.
- The size gives us information on the size of the list.
- Since the size is 2, the last index we can access is (2-1)=1, and thus the exception.
The correct way to access the array is :
Correct Code –
Handling the Exception:
1. Using for-each loop:
This automatically handles indices while accessing the elements of an array.
Syntax:
Example:
2. Using Try-Catch:
Consider enclosing your code inside a try-catch statement and manipulate the exception accordingly. As mentioned, Java won’t let you access an invalid index and will definitely throw an ArrayIndexOutOfBoundsException. However, we should be careful inside the block of the catch statement because if we don’t handle the exception appropriately, we may conceal it and thus, create a bug in your application.
Here in the above example, you can see that till index 4 (value 5), the loop printed all the values, but as soon as we tried to access the arr[5], the program threw an exception which is caught by the catch block, and it printed the “Exception caught” statement.