Andrew Engen
Andrew Engen

Reputation: 9

How to make code ignore ArrayIndexOutOfBoundsException java

I was wondering if there is a way in java, when iterating through an array and placing values in certain indices, to skip an out of bounds exception and just go to the next item.

For instance,

           for (int x = 0; x <= array.length; x++) 
           {
               for (int y = 0; y <= array[0].length; x++)
               {
                   // code that determines where to put things and in what indices

                   //if this index is out of the array bounds, I want to forget about it and keep going through the loops

               }

               }

           }

Upvotes: 0

Views: 2542

Answers (4)

PermGenError
PermGenError

Reputation: 46418

I was wondering if there is a way in java, when iterating through an array and placing values in certain indices, to skip an out of bounds exception and just go to the next item

If index is out of bounds at certain index, then the next index is certainly out of bounds as well. For your code to work just do.

 for (int x = 0; x <array.length; x++) 
           {
               for (int y = 0; y <array[x].length; y++)
               {

Array indexes are zero based. i.e.

If the length of the array is n, then last index of the array would ne n-1

Upvotes: 3

ridoy
ridoy

Reputation: 6332

The problem means that you used index on array which is invalid. That could negative number, because all arrays starts from 0. If you array has N items and you will try to get item with index N or higher you will get this exception too. Only available indexes are from 0 to N - 1, where 0 points to the first item and N - 1 to the last one.So clearly when your index goes out of bounds than your array limits,the next index will definitely out of bounds.So you can iterate the index until it goes out of bounds and stop iteration there to avoid that exception.

Upvotes: 0

Maroun
Maroun

Reputation: 95968

Arrays indexes begins from 0.

So when you have an Array of length 100 for example, then the indexes are:

  0   1   2   3   4   5  ..... 99   (total size of 100 of course)
  ^   ^   ^   ^   ^   ^        ^
  |   |   |   |   |   |        |
first                         last

When you do array.length you actually get 100, but you need to iterate until 99.

So, replace <= with <

Upvotes: 0

christopher
christopher

Reputation: 27346

Right. First things first, the update section of your nested loop should say y++. Not x++. That code would just cycle ad infinitum.

Secondly, you can wrap the loop in a try-catch and this will catch the exception, but it's not recommended to just ignore an exception. Why not design your code so it doesn't throw the exception?

Upvotes: 0

Related Questions