BackendBench
Coffee

Home โ€บ Java exceptions โ€บ IndexOutOfBoundsException

Unchecked exception ยท java.lang

IndexOutOfBoundsException: causes and fixes

A List or other indexed collection was accessed with an index outside its size.

What it looks like

java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3

Extends RuntimeException in java.lang.

What it means

List implementations such as ArrayList throw IndexOutOfBoundsException from get, set, add(index, e) and remove(index) when the index is negative or not smaller than the size. It is the parent of ArrayIndexOutOfBoundsException and StringIndexOutOfBoundsException. An empty list is the most common trigger, because index 0 is already out of range.

Common causes

How to fix it

  1. Check isEmpty() or size() before indexing.
  2. Use streams or findFirst() to get an Optional instead of get(0).
  3. Iterate with an Iterator and remove(), or use removeIf, when deleting while looping.
  4. Use List.getFirst() and getLast() (Java 21) when you really want the ends; they throw a clearer NoSuchElementException.

Broken and fixed

fails
List<Order> orders = repo.findByCustomer(id);
Order first = orders.get(0); // empty list -> exception
works
Order first = orders.stream().findFirst()
        .orElseThrow(() -> new OrderNotFoundException(id));

๐Ÿ”Ž Unravel the failing code ๐Ÿ”Ž Unravel the fix

In Spring and enterprise code

Repository and query methods return empty lists, not null, so get(0) without a size check is a very common production error in service code.

Debug it faster

Paste the whole stack trace into the stack trace beautifier to hide framework frames, jump to the root cause and find the first line of your own code. It runs in your browser, so the trace never leaves your machine.

Frequently asked questions

Is IndexOutOfBoundsException a checked or unchecked exception?

IndexOutOfBoundsException is an unchecked exception (it extends RuntimeException), so you are not forced to catch it. Prevent it with validation, or handle it where the input enters the system.

Which package is IndexOutOfBoundsException in?

It lives in java.lang, so the import is import java.lang.IndexOutOfBoundsException; (java.lang needs no import).

What is the first thing to check when I see IndexOutOfBoundsException?

Read the message and the first stack trace line in your own code. The usual causes are: Calling list.get(0) on a list that is empty, for example a query that returned no rows; and Removing elements inside a loop that counts up, which shifts the remaining indexes.

Related exceptions

More tools you might need