Java : IndexOutOfBoundsException with Examples

IndexOutOfBoundsException (Java SE 21 & JDK 21) with Examples.
You will find code examples on most IndexOutOfBoundsException methods.


Summary

Thrown to indicate that an index of some sort (such as to an array, to a string, or to a vector) is out of range.

Class diagram

final String[] array = {"aaa", "bbb", "ccc"};

System.out.println(array[0]); // aaa
System.out.println(array[1]); // bbb
System.out.println(array[2]); // ccc

try {
    final var ret = array[4];
} catch (IndexOutOfBoundsException e) {
    System.out.println("IndexOutOfBoundsException! : " + e.getMessage());
}

// Result
// ↓
//IndexOutOfBoundsException! : Index 4 out of bounds for length 3

Constructors

IndexOutOfBoundsException ()

Constructs an IndexOutOfBoundsException with no detail message.

final var e = new IndexOutOfBoundsException();
System.out.println(e); // java.lang.IndexOutOfBoundsException

IndexOutOfBoundsException (int index)

Constructs a new IndexOutOfBoundsException class with an argument indicating the illegal index.

final var e = new IndexOutOfBoundsException(123);

// java.lang.IndexOutOfBoundsException: Index out of range: 123
System.out.println(e);

IndexOutOfBoundsException (long index)

Constructs a new IndexOutOfBoundsException class with an argument indicating the illegal index.

final var e = new IndexOutOfBoundsException(10000000000L);

// java.lang.IndexOutOfBoundsException: Index out of range: 10000000000
System.out.println(e);

IndexOutOfBoundsException (String s)

Constructs an IndexOutOfBoundsException with the specified detail message.

final var e = new IndexOutOfBoundsException("abcd");
System.out.println(e); // java.lang.IndexOutOfBoundsException: abcd

Methods declared in Throwable

addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString

Please see the link below.


Related posts

To top of page