IndexOutOfBoundsException
What is IndexOutOfBoundsException?
IndexOutOfBoundsException: The code tries to access an element in an array (or list) at an index that does not exist. An IndexOutOfBoundsException, or a similar error in other languages, means the code tried to read a position in a list that does not exist. Asking for item 10 in a list of five, or item 0 in an empty list, are the usual cases.
Frequently asked questions about IndexOutOfBoundsException
How is IndexOutOfBoundsException used in practice?
In Java and C# this throws an exception. PHP gives an "Undefined array key" warning and returns null, and JavaScript simply returns undefined, which can cause errors much later.
What should you keep in mind with IndexOutOfBoundsException?
The classic causes are off-by-one mistakes in loops, assuming a query always returns results, or taking the first element of an empty array. Check for emptiness before accessing, use methods like first() that return null safely, and iterate with foreach instead of manual index counting where possible. Tests with empty and single-item lists catch most of these.
At a glance
| Category | Error types |
|---|---|
| Explained by | Reinier de la Parra |
| Updated |