Java : ArrayIndexOutOfBoundsException with Examples
ArrayIndexOutOfBoundsException (Java SE 21 & JDK 21) with Examples.
You will find code examples on most ArrayIndexOutOfBoundsException methods.
Summary
Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
final int[] array = {10, 20, 30};
System.out.println(array[0]); // 10
System.out.println(array[1]); // 20
System.out.println(array[2]); // 30
try {
final var ret = array[3];
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}
// Result
// ↓
//java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
Constructors
ArrayIndexOutOfBoundsException ()
Constructs an ArrayIndexOutOfBoundsException with no detail message.
final var e = new ArrayIndexOutOfBoundsException();
System.out.println(e); // java.lang.ArrayIndexOutOfBoundsException
ArrayIndexOutOfBoundsException (int index)
Constructs a new ArrayIndexOutOfBoundsException class with an argument indicating the illegal index.
final var e = new ArrayIndexOutOfBoundsException(123);
// java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 123
System.out.println(e);
ArrayIndexOutOfBoundsException (String s)
Constructs an ArrayIndexOutOfBoundsException class with the specified detail message.
final var e = new ArrayIndexOutOfBoundsException("abcd");
System.out.println(e); // java.lang.ArrayIndexOutOfBoundsException: 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
- API Examples
- Error
- Exception
- RuntimeException
- ArithmeticException
- ArrayStoreException
- CancellationException
- ClassCastException
- ConcurrentModificationException
- DateTimeException
- DateTimeParseException
- IllegalArgumentException
- IllegalStateException
- IndexOutOfBoundsException
- NoSuchElementException
- NullPointerException
- PatternSyntaxException
- StringIndexOutOfBoundsException
- UnsupportedOperationException
- Throwable