Bazaprogram.ru

Новости из мира ПК
3 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Java lang indexoutofboundsexception

Java Exception Handling – IndexOutOfBoundsException

Moving along through the detailed Java Exception Handling series we’ve been working on, today we’ll be going over the IndexOutOfBoundsException. The IndexOutOfBoundsException is thrown when attempting to access an invalid index within a collection, such as an array , vector , string , and so forth. It can also be implemented within custom classes to indicate invalid access was attempted for a collection.

In this article we’ll explore the IndexOutOfBoundsException by starting with where it resides in the overall Java Exception Hierarchy. We’ll also examine some fully functional Java code samples that will illustrate both the default API invocation of IndexOutOfBoundsExceptions , along with a custom class example of how you might throw them in your own code. Let’s get crackin’!

The Technical Rundown

All Java errors implement the java.lang.Throwable interface, or are extended from another inherited class therein. The full exception hierarchy of this error is:

Full Code Sample

Below is the full code sample we’ll be using in this article. It can be copied and pasted if you’d like to play with the code yourself and see how everything works.

When Should You Use It?

Coming across an IndexOutOfBoundsException in standard API code simply means an invalid index was accessed for a collection. To illustrate we have two methods, createArrayOfSize(int size) and getElementByIndex(int[] array, int index) :

As you can see, createArrayOfSize(int size) just creates and returns a new int[] array of the specified size, populating elements with random integers. We then use getElementByIndex(int[] array, int index) to attempt to retrieve specific elements of the passed int[] array parameter that correspond with the specified int index parameter.

To test this out we’ll start by creating a 10-length array, output it to the log, then attempt to retrieve a specific element at index 5 :

Here’s the output we get after executing the above code:

Everything seems to be working as expected. Our initial array contains 10 random integers and the element at index 5 is 85 , as confirmed by the call to getElementByIndex(int[] array, int index) .

Now, let’s try getting an element at an index outside the bounds of our array ( 10 , in this case):

The output shows we’ve thrown a specific ArrayIndexOutOfBoundsException , which is an exception class that inherits from IndexOutOfBoundsException :

That’s all well and good, but what happens if we want a more descriptive exception message? We can implement IndexOutOfBoundsExceptions directly into our own custom classes, to be thrown when attempts to access an invalid index would cause problems. For example, we’ve created a simple Page class that contains a single content field to store the content of the Page :

We then have a modified Book class that contains a Page[] pages field array, allowing us to specify a series of Page elements associated with the Book . We have methods to both get and set Pages within the Book instance, but the most important method is setPage(Page page, int index) , which allows us to explicitly change the Page element at the specified int index . However, if the passed index is invalid or exceeds the current bounds of our pages field length, we explicitly throw a new IndexOutOfBoundsException indicating the problem:

To test this out we start by instantiating a new Book and adding some content to the first few three pages:

This produces the initial Book output without any Pages content, then once we add them via the setPages(Page[] pages) method, the output shows our Pages have been added successfully:

Cool! Now let’s try this setPageAtIndex(Book, book, Page page, int index) helper method, which is just a wrapper for the Book.setPage(Page page, int index) method:

Here we’re passing our previous book instance, a new fourth Page , and an index of 3 (to indicate the fourth page):

Since we explicitly check the validity of the passed int index parameter in Book.setPage(Page page, int index) , this attempt to set a Page for an invalid index throws our custom IndexOutOfBoundsException :

Читать еще:  Java io ioexception

The Airbrake-Java library provides real-time error monitoring and automatic exception reporting for all your Java-based projects. Tight integration with Airbrake’s state of the art web dashboard ensures that Airbrake-Java gives you round-the-clock status updates on your application’s health and error rates. Airbrake-Java easily integrates with all the latest Java frameworks and platforms like Spring , Maven , log4j , Struts , Kotlin , Grails , Groovy , and many more. Plus, Airbrake-Java allows you to easily customize exception parameters and gives you full, configurable filter capabilities so you only gather the errors that matter most.

Check out all the amazing features Airbrake-Java has to offer and see for yourself why so many of the world’s best engineering teams are using Airbrake to revolutionize their exception handling practices!

Понимание Array IndexOutofbounds Исключение в Java

Java поддерживает создание и манипулирование массивами , как структуру данных. Индекс массива — это целочисленное значение, значение которого находится в интервале [0, n-1], где n — размер массива. Если сделан запрос на отрицательный или индекс, который больше или равен размеру массива, то JAVA выдает исключение ArrayIndexOutOfBounds. Это не похоже на C / C ++, где не выполняется проверка индекса привязки.

ArrayIndexOutOfBoundsException — исключение времени выполнения, выдаваемое только во время выполнения. Компилятор Java не проверяет эту ошибку во время компиляции программы.

// Индекс общей причины выходит за пределы

public class NewClass2

public static void main(String[] args)

for ( int i= 0 ; i

Ошибка выполнения выдает исключение:

Выход:

Здесь, если вы внимательно посмотрите, массив имеет размер 5. Следовательно, при доступе к его элементу с помощью цикла for максимальное значение индекса может быть 4, но в нашей программе оно увеличивается до 5 и, следовательно, является исключением.

Давайте посмотрим еще один пример использования arraylist:

// Еще один пример с индексом вне границ

public class NewClass2

public static void main(String[] args)

ArrayList lis = new ArrayList<>();

Ошибка выполнения здесь немного более информативна, чем предыдущая

Давайте поймем это немного подробнее

  • Индекс здесь определяет индекс, к которому мы пытаемся получить доступ.
  • Размер дает нам информацию о размере списка.
  • Поскольку размер равен 2, последний индекс, к которому мы можем получить доступ (2-1) = 1, и, следовательно, исключение

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

Обработка исключения:

  • Использовать цикл for-each : он автоматически обрабатывает индексы при доступе к элементам массива. Пример-
  • Используйте Try-Catch: рассмотрите возможность включения вашего кода в оператор try-catch и соответственно обработайте исключение. Как уже упоминалось, Java не позволит вам получить доступ к недопустимому индексу и обязательно выдаст исключение ArrayIndexOutOfBoundsException. Однако мы должны быть осторожны внутри блока оператора catch, потому что, если мы не обработаем исключение надлежащим образом, мы можем скрыть его и, таким образом, создать ошибку в вашем приложении.

Эта статья предоставлена Rishabh Mahrsee . Если вам нравится GeeksforGeeks и вы хотите внести свой вклад, вы также можете написать статью и отправить ее по почте на contrib@geeksforgeeks.org. Смотрите свою статью, появляющуюся на главной странице GeeksforGeeks, и помогите другим вундеркиндам.

Пожалуйста, напишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по обсуждаемой теме

Java Exception Handling – IndexOutOfBoundsException

Moving along through the detailed Java Exception Handling series we’ve been working on, today we’ll be going over the IndexOutOfBoundsException. The IndexOutOfBoundsException is thrown when attempting to access an invalid index within a collection, such as an array , vector , string , and so forth. It can also be implemented within custom classes to indicate invalid access was attempted for a collection.

In this article we’ll explore the IndexOutOfBoundsException by starting with where it resides in the overall Java Exception Hierarchy. We’ll also examine some fully functional Java code samples that will illustrate both the default API invocation of IndexOutOfBoundsExceptions , along with a custom class example of how you might throw them in your own code. Let’s get crackin’!

The Technical Rundown

All Java errors implement the java.lang.Throwable interface, or are extended from another inherited class therein. The full exception hierarchy of this error is:

Читать еще:  Java security cert certpathvalidatorexception

Full Code Sample

Below is the full code sample we’ll be using in this article. It can be copied and pasted if you’d like to play with the code yourself and see how everything works.

When Should You Use It?

Coming across an IndexOutOfBoundsException in standard API code simply means an invalid index was accessed for a collection. To illustrate we have two methods, createArrayOfSize(int size) and getElementByIndex(int[] array, int index) :

As you can see, createArrayOfSize(int size) just creates and returns a new int[] array of the specified size, populating elements with random integers. We then use getElementByIndex(int[] array, int index) to attempt to retrieve specific elements of the passed int[] array parameter that correspond with the specified int index parameter.

To test this out we’ll start by creating a 10-length array, output it to the log, then attempt to retrieve a specific element at index 5 :

Here’s the output we get after executing the above code:

Everything seems to be working as expected. Our initial array contains 10 random integers and the element at index 5 is 85 , as confirmed by the call to getElementByIndex(int[] array, int index) .

Now, let’s try getting an element at an index outside the bounds of our array ( 10 , in this case):

The output shows we’ve thrown a specific ArrayIndexOutOfBoundsException , which is an exception class that inherits from IndexOutOfBoundsException :

That’s all well and good, but what happens if we want a more descriptive exception message? We can implement IndexOutOfBoundsExceptions directly into our own custom classes, to be thrown when attempts to access an invalid index would cause problems. For example, we’ve created a simple Page class that contains a single content field to store the content of the Page :

We then have a modified Book class that contains a Page[] pages field array, allowing us to specify a series of Page elements associated with the Book . We have methods to both get and set Pages within the Book instance, but the most important method is setPage(Page page, int index) , which allows us to explicitly change the Page element at the specified int index . However, if the passed index is invalid or exceeds the current bounds of our pages field length, we explicitly throw a new IndexOutOfBoundsException indicating the problem:

To test this out we start by instantiating a new Book and adding some content to the first few three pages:

This produces the initial Book output without any Pages content, then once we add them via the setPages(Page[] pages) method, the output shows our Pages have been added successfully:

Cool! Now let’s try this setPageAtIndex(Book, book, Page page, int index) helper method, which is just a wrapper for the Book.setPage(Page page, int index) method:

Here we’re passing our previous book instance, a new fourth Page , and an index of 3 (to indicate the fourth page):

Since we explicitly check the validity of the passed int index parameter in Book.setPage(Page page, int index) , this attempt to set a Page for an invalid index throws our custom IndexOutOfBoundsException :

The Airbrake-Java library provides real-time error monitoring and automatic exception reporting for all your Java-based projects. Tight integration with Airbrake’s state of the art web dashboard ensures that Airbrake-Java gives you round-the-clock status updates on your application’s health and error rates. Airbrake-Java easily integrates with all the latest Java frameworks and platforms like Spring , Maven , log4j , Struts , Kotlin , Grails , Groovy , and many more. Plus, Airbrake-Java allows you to easily customize exception parameters and gives you full, configurable filter capabilities so you only gather the errors that matter most.

Check out all the amazing features Airbrake-Java has to offer and see for yourself why so many of the world’s best engineering teams are using Airbrake to revolutionize their exception handling practices!

Читать еще:  Unexpected identifier javascript

Solving java.lang.ArrayindexOutOfBoundsException: 1 in Java

The error ArrayIndexOutOfBoundsException : 1 means index 1 is inval >ArrayIndexOutfBoundsException comes when your code, mostly for loop tries to access an inval >IndexOutOfBoundsException which is used to throw error related to invalid index e.g. try to access outside of length in String etc.

An array is a data structure which is the base for many advanced data structure e.g. list, hash table or a binary tree. The array stores elements in the contiguous memory location and it can also have multiple dimension e.g. a two-dimensional array. You can use the 2D array to represent matrix, a board in games like Tetris, Chess and other board games.

A good knowledge of data structure and the algorithm is a must for any good programmer. You should read a good introductory book e.g. Introduction to Algorithms by Thomas Cormen to learn more about array in Java.

Understanding ArrayIndexOutOfBoundsException

This error comes when you are accessing or iterating over array directly or indirectly. Directly means you are dealing with array type e.g. String[] or main method, or an integer[] you have created in your program. Indirectly means via Collection classes which internally use an array e.g. ArrayList or HashMap.

Now let’s understand what information the associated error message gives us:
java.lang.ArrayIndexOutOfBoundsException: 0 means you are trying to access index 0 which is invalid, which in turn means the array is empty.

Here is a Java program which reproduces this error by accessing the first element of the empty array i.e. array with zero length:

You can see the accessing first element of an empty array resulted in the ArrayIndexOutOfBoundsException in Java.

java.lang.ArrayindexOutOfBoundsException: 1 means index 1 is invalid, which in turn means array contains just one element. Here is a Java program which will throw this error:

Similarly, java.lang.ArrayIndexOutOfBoundsException: 2 means index 2 is invalid, which means array has just 2 elements and you are trying to access the third element of the array.

Sometimes when a programmer makes switch from C/C++ to Java they forget that Java does the bound checking at runtime, which is a major difference between C++ and Java Array. You should read Core Java Volume 1 By Cay S. Horstmann if you are learning Java and knows C++. The author often highlights the key difference between C++ and Java while teaching important concepts.

Here is nice slide of some good tips to avoid ArrayIndexOutOfBondsException in Java:

How to avoid ArrayIndexOutOfBoundsException in Java

In order to avoid the java.lang.ArrayIndexOutOfBoundsException, you should always do the bound check before accessing array element e.g.

Always remember that array index starts at 0 and not 1 and an empty array has no element in it. So accessing the first element will give you the java.lang.ArrayIndexOutOfBoundsException : 0 error in Java.

You should always pay to one-off errors while looping over an array in Java. The programmer often makes mistakes which result in either missing first or last element of the array by messing 1st element or finishing just before the last element by incorrectly using the , >= or operator in for loops. For example, following program will never print the last element of the array. The worst part is there won’t be any compile time error or runtime exception. It’s pure logical error which will cause incorrect calculation.

You can see the first element of array i.e. 2 is never get printed. There is no compile time or runtime error, though.

Here are few handy tips to avoid ArrayIndexOutOfBoundsException in Java:

  1. Always remember that array is zero based index, first element is at 0th index and last element is at length — 1 index.
  2. Pay special attention to start and end condition of loop.
  3. Beware of one-off errors like above.
Ссылка на основную публикацию
Adblock
detector