Меню Закрыть

Exception in thread main java lang arrayindexoutofboundsexception

Содержание

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

Попробуйте выполнить такой код:

Вы увидите ошибку:

Что здесь произошло? Ошибка в строке 27 – мы вызвали метод deposit(), а в нем уже, в строке 22 – попытались внести в поле массива значение "deposit". Почему выкинуло исключение? Дело в том, что мы инициализировали массив размера 11 (number = 11), н опопытались обратиться к 12-му элементу. Нумерация элементов массива начинается с нуля. Так что здесь надо сделать, например, так

Но вообще, это плохой код, так писать не надо. Давайте рассмотрим еще один пример возникновения ошибки ArrayIndexOutOfBoundsException:

Здесь массив заполняется случайными значениями. При выполнении IntelliJ IDEA выдаст ошибку

Не могу разобраться в чем ошибка.

КОД:

2 ответа 2

Логично. Ведь когда цикл в sortArray доходит до последнего элемента и попадает на строку

то i + 1 указывает на элемент за границей массива

If you are coming from C background than there is pleasant surprise for you, Java programming language prov >IndexOutOfBoundsException if inval >get(int index) methods. One of the common mistakes Java programmer makes is invalid end condition on classical index based for loops.

Since more often than not, you write code to loop over array or list in Java, a wrong end condition can result in Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException, as shown in next section.

Along with java.lang.NullPointerException , this exception is biggest problem for new-comers, but, easiest to solve, once you know the basics.

Читайте также:  Дискретная видеокарта как увеличить память

As name suggests, ArrayIndexOutOfBoundsException comes, when you try to access an invalid bound i.e. index. Array is fixed length data structure, once created and initialized, you cannot change its size.

If an array is created with size 5 means it has five slots to hold items depending upon type of array, and it’s index is zero based, which means first item exits in index 0 , second at index 1, and last element at index 4 [length-1] , this is where most mistakes are made. For getting a refresher in array, please see Java Array 101.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5

Now let’s diagnose this error message, which I guess every Java programmer has seen during his learning experience. "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException : 5" says that, our code has got java.lang.ArrayIndexOutOfBoundsException , while accessing an index 5 , which also that means index 5 is illegal for this array.

If you look closely, It also tells us that this Exception has occurred in main thread and because it was uncaught, main thread has finished abruptly and so is our Java program. Now let’s look at our code, which is causing this error :

Can you sport the mistake? Yes, it’s subtle and not easy to find if you are new to Java. Condition in for loop is wrong, it should be i instead of i , because array index starts at zero. Due to this error, our for loop runs one iteration more than expected and though our program correctly prints all supported currencies, it died due to uncaught java.lang.ArrayIndexOutOfBoundsException in the end . This error comes when loop runs at 6th time, to access 6th element (index 5). That’s why you should always pay attention, while looping over array in Java. You can also see your array’s content at runtime by debugging your Java program in Eclipse. Just setup a breakpoint at the line, where you initialize the array and then just look at variables window in debug perspective of Eclipse IDE. You can see your array in tabular format as shown below :

Читайте также:  Intel core i7 960 характеристики

Iterating Over Array using ForEach Loop

Alternatively you can also use advanced for-each loop from Java 5, which doesn’t require an index, instead it automatically calculates index during iteration over array, as shown below :

Things to remember about ArrayIndexOutOfBoundsException in Java

One of the most important thing to solve any error is to know more about that error. Rather than being reactive, be proactive. As part of your learning process you should know in and out of IndexOfBoundsException and particularly ArrayIndexOutOfBoundsException . Here is some of the important details of this beginner’s nemesis :

1) Like java.lang.NullPointerException, this is also an unchecked exception in Java. It’s sub- >RuntimeException and doesn’t need to be declared by throws clause, but it’s better to document if your method can throw ArrayIndexOutBoundsException .

2) It’s also sub- >IndexOutOfBoundsException in Java, which means if you have a catch block for catching IndexOutOfBoundsException , you will implicitly catch java.lang.ArrayIndexOutOfBoundsException as shown below :

You can see, we haven’t got "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5" , rather we just got "java.lang.ArrayIndexOutOfBoundsException: 5", because this time we have caught the exception, which means main thread is not died and finished normally.

3) Java is safe programming language and that’s why you get this error when you try to access an out of bound index, this way Java prevents many malicious attacks, which is possible in C programming language.

4) Always remember, size of array is same as length of array and index starts from zero. So an array of size 5 or length 5 can contain five elements, but valid indexes are 0 to 4. Negative index is also invalid.

Рекомендуем к прочтению

Добавить комментарий

Ваш адрес email не будет опубликован.