- How to handle Java Array Index Out of Bounds Exception?
- Example
- Output
- Handling the exception
- Example
- Output
- Ошибка ArrayIndexOutOfBoundsException Java
- How to Fix the Array Index Out Of Bounds Exception in Java
- What Causes ArrayIndexOutOfBoundsException
- ArrayIndexOutOfBoundsException Example
- How to Fix ArrayIndexOutOfBoundsException
- Track, Analyze and Manage Errors With Rollbar
How to handle Java Array Index Out of Bounds Exception?
Generally, an array is of fixed size and each element is accessed using the indices. For example, we have created an array with size 9. Then the valid expressions to access the elements of this array will be a[0] to a[8] (length-1).
Whenever you used an –ve value or, the value greater than or equal to the size of the array, then the ArrayIndexOutOfBoundsException is thrown.
For Example, if you execute the following code, it displays the elements in the array asks you to give the index to select an element. Since the size of the array is 7, the valid index will be 0 to 6.
Example
import java.util.Arrays; import java.util.Scanner; public class AIOBSample < public static void main(String args[]) < int[] myArray = ; System.out.println("Elements in the array are:: "); System.out.println(Arrays.toString(myArray)); Scanner sc = new Scanner(System.in); System.out.println("Enter the index of the required element ::"); int element = sc.nextInt(); System.out.println("Element in the given index is :: "+myArray[element]); > >
But if you observe the below output we have requested the element with the index 9 since it is an invalid index an ArrayIndexOutOfBoundsException raised and the execution terminated.
Output
Elements in the array are:: [897, 56, 78, 90, 12, 123, 75] Enter the index of the required element :: 7 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7 at AIOBSample.main(AIOBSample.java:12)
Handling the exception
You can handle this exception using try catch as shown below.
Example
import java.util.Arrays; import java.util.Scanner; public class AIOBSampleHandled < public static void main(String args[]) < int[] myArray = ; System.out.println("Elements in the array are:: "); System.out.println(Arrays.toString(myArray)); Scanner sc = new Scanner(System.in); System.out.println("Enter the index of the required element ::"); try < int element = sc.nextInt(); System.out.println("Element in the given index is :: "+myArray[element]); >catch(ArrayIndexOutOfBoundsException e) < System.out.println("The index you have entered is invalid"); System.out.println("Please enter an index number between 0 and 6"); >> >
Output
Elements in the array are:: [897, 56, 78, 90, 12, 123, 75] Enter the index of the required element :: 7 The index you have entered is invalid Please enter an index number between 0 and 6
Ошибка ArrayIndexOutOfBoundsException Java
ArrayIndexOutOfBoundsException – это исключение, появляющееся во время выполнения. Оно возникает тогда, когда мы пытаемся обратиться к элементу массива по отрицательному или превышающему размер массива индексу. Давайте посмотрим на примеры, когда получается ArrayIndexOutOfBoundsException в программе на Java.
Попробуйте выполнить такой код:
static int number=11; public static String[][] transactions=new String[8][number]; public static void deposit(double amount) < transactions[4][number]="deposit"; number++; >public static void main(String[] args) < deposit(11); >>
Caused by: java.lang.ArrayIndexOutOfBoundsException: 0 at sample.Main.deposit(Main.java:22) at sample.Main.main(Main.java:27) Exception running application sample.Main Process finished with exit code 1
Что здесь произошло? Ошибка в строке 27 – мы вызвали метод deposit(), а в нем уже, в строке 22 – попытались внести в поле массива значение «deposit». Почему выкинуло исключение? Дело в том, что мы инициализировали массив размера 11 (number = 11), н опопытались обратиться к 12-му элементу. Нумерация элементов массива начинается с нуля. Так что здесь надо сделать, например, так
public static String[][] transactions=new String[8][100];
Но вообще, это плохой код, так писать не надо. Давайте рассмотрим еще один пример возникновения ошибки ArrayIndexOutOfBoundsException:
public static void main(String[] args) < Random random = new Random(); int [] arr = new int[10]; for (int i = 0; i >
Здесь массив заполняется случайными значениями. При выполнении IntelliJ IDEA выдаст ошибку
Caused by: java.lang.ArrayIndexOutOfBoundsException: 10 at sample.Main.main(Main.java:37)
В строке 37 мы заносим значение в массив. Ошибка возникла помтому, что индекса 10 нет в массиве arr, поэтому условие цикла i <= arr.length надо поменять на i < arr.length
=>
Конструкция try для ArrayIndexOutOfBoundsException
ArrayIndexOutOfBoundsException можно обработать с помощью конструкции try-catch. Для этого оберните try то место, где происходит обращение к элементу массива по индексу, например, заносится значение. Как-то так:
try < array[index] = "что-то"; >catch (ArrayIndexOutOfBoundsException ae)
Но я бы рекомендовал вам все же не допускать данной ошибки, писать код таким образом, чтобы не пришлось ловить исключение ArrayIndexOutOfBoundsException.
Автор этого материала — я — Пахолков Юрий. Я оказываю услуги по написанию программ на языках Java, C++, C# (а также консультирую по ним) и созданию сайтов. Работаю с сайтами на CMS OpenCart, WordPress, ModX и самописными. Кроме этого, работаю напрямую с JavaScript, PHP, CSS, HTML — то есть могу доработать ваш сайт или помочь с веб-программированием. Пишите сюда.
заметки, ArrayIndexOutOfBoundsException, java, ошибки, исключения
How to Fix the Array Index Out Of Bounds Exception in Java
The ArrayIndexOutOfBoundsException is a runtime exception in Java that occurs when an array is accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
Since the ArrayIndexOutOfBoundsException is an unchecked exception, it does not need to be declared in the throws clause of a method or constructor.
What Causes ArrayIndexOutOfBoundsException
The ArrayIndexOutOfBoundsException is one of the most common errors in Java. It occurs when a program attempts to access an invalid index in an array i.e. an index that is less than 0, or equal to or greater than the length of the array.
Since a Java array has a range of [0, array length — 1], when an attempt is made to access an index outside this range, an ArrayIndexOutOfBoundsException is thrown.
ArrayIndexOutOfBoundsException Example
Here is an example of a ArrayIndexOutOfBoundsException thrown when an attempt is made to retrieve an element at an index that falls outside the range of the array:
public class ArrayIndexOutOfBoundsExceptionExample < public static void main(String[] args) < String[] arr = new String[10]; System.out.println(arr[10]); > >
In this example, a String array of length 10 is created. An attempt is then made to access an element at index 10, which falls outside the range of the array, throwing an ArrayIndexOutOfBoundsException :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10 at ArrayIndexOutOfBoundsExceptionExample.main(ArrayIndexOutOfBoundsExceptionExample.java:4)
How to Fix ArrayIndexOutOfBoundsException
To avoid the ArrayIndexOutOfBoundsException , the following should be kept in mind:
- The bounds of an array should be checked before accessing its elements.
- An array in Java starts at index 0 and ends at index length — 1 , so accessing elements that fall outside this range will throw an ArrayIndexOutOfBoundsException .
- An empty array has no elements, so attempting to access an element will throw the exception.
- When using loops to iterate over the elements of an array, attention should be paid to the start and end conditions of the loop to make sure they fall within the bounds of an array. An enhanced for loop can also be used to ensure this.
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!