Java StringIndexOutOfBoundsException
Example
Get a character at an index that does not exist, and catch the exception:
public class Main {
public static void main(String[] args) {
String text = "Hello";
try {
System.out.println(text.charAt(10));
} catch (StringIndexOutOfBoundsException e) {
System.out.println("The index does not exist in the string.");
}
}
}
Definition and Usage
A StringIndexOutOfBoundsException happens when you use an index (a position) that does not exist in a string, for example with charAt() or substring(). Indexes start at 0, so the last index is one less than the length of the string.
Check the index first: it must be 0 or more, and less than text.length().
Related Pages
Java Exceptions (try...catch) Tutorial
❮ Errors & Exceptions