Many of the methods of the class String have an argument that is an integer that is the position of a character within a string. If you pass an argument that is invalid, the method will signify that it cannot handle this situation, by throwing an exception called StringIndexOutOfBoundsException. An exception is an occurrence of an exceptional circumstance, a situation that does not normally occur.
For example, if you call charAt with the value 5 when a string has 5 characters, your program will crash displaying lines like:
java.lang.StringIndexOutOfBoundsException: String index out of range: 5
at java.lang.String.charAt(String.java)
at StringIndexTest.main(StringIndexTest.java:6)
Instead of letting the program crash like this, we can include code in our program that will be executed when an exception occurs. Java has a statement called a try statement that is used to handle exceptions, and we will look at try statements later.
Java divides exceptions into two categories: checked exceptions and unchecked exceptions. A StringIndexOutOfBoundsException is an unchecked exception, and Java says that a program does not have to say what it wants to happen when an unchecked exception occurs.