Java Exception Handling

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:

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!