Blog |

How to Handle String Index Out Of Bounds Exception in Java

How to Handle String Index Out Of Bounds Exception in Java
Table of Contents
Try Rollbar Today

Proactively discover and resolve errors

The StringIndexOutOfBoundsException is an unchecked exception in Java that occurs when an attempt is made to access the character of a string at an index which is either negative or greater than the length of the string.

For some methods of the String class, such as the charAt method, this exception is also thrown when the index is equal to the size of the string.

Since the StringIndexOutOfBoundsException is an unchecked exception, it does not need to be declared in the throws clause of a method or constructor. It can be handled in code using a try-catch block.

 

What Causes StringIndexOutOfBoundsException

A Java string is a collection of characters which has a range of [0, length of string]. When an attempt is made to access the characters with limits that fall outside the range of the string, the StringIndexOutOfBoundsException is thrown. Therefore, this exception occurs when the index of a character does not exist in the string.

Some methods that throw a StringIndexOutOfBoundsException with invalid specified arguments are:

  • String.charAt(int index) - Returns the character at the specified index. The index can have a range of [0, length - 1]. If the specified index does not belong to this range, a StringIndexOutOfBoundsException occurs.
  • CharSequence.subSequence(int beginIndex, int endIndex) - Returns a new character sequence based on specified arguments. The StringIndexOutOfBoundsException is thrown if any index is negative, the endIndex is greater than the length of the string or the beginIndex is greater than the endIndex.
  • String.substring(int beginIndex) - Returns a substring beginning with the character at the specified index. If the beginIndex is negative or greater than the length of the string, a StringIndexOutOfBoundsException is thrown.
  • String.substring(int beginIndex, int endIndex) - Returns a substring beginning with the character at the specified index, extending until the character at (endIndex - 1). The StringIndexOutOfBoundsException is thrown if any index is negative, the endIndex is greater than the length of the string or the beginIndex is greater than the endIndex.
  • String.valueOf(char[] data, int offset, int count) - Returns the string representation of the specified character array argument. If any index is negative or if (offset + count) is greater than the size of the specified array, a StringIndexOutOfBoundsException is thrown.

Also, all constructors of the String class that contain an array in their argument list throw a StringIndexOutOfBoundsException when the specified offset and count arguments are invalid.

 

StringIndexOutOfBoundsException Example

Here is an example of a StringIndexOutOfBoundsException thrown when an attempt is made to retrieve the character at a specified index that falls outside the range of the string:

public class StringIndexOutOfBoundsExceptionExample {
    public static void main(String args[]) {
        String str = "My String";
        System.out.println(str.charAt(9));
    }
}

In this example, the String.charAt() method is used to access the character at index 9. Since this method only allows a range of [0, length - 1] for the string, using index 9 throws the StringIndexOutOfBoundsException as it falls outside the range:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 9
    at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)
    at java.base/java.lang.String.charAt(String.java:711)
    at StringIndexOutOfBoundsExceptionExample.main(StringIndexOutOfBoundsExceptionExample.java:4)

 

How to Handle StringIndexOutOfBoundsException

The StringIndexOutOfBoundsException is an exception in Java, and therefore can be handled using try-catch blocks using the following steps:

  • Surround the statements that can throw an StringIndexOutOfBoundsException in try-catch blocks
  • Catch the StringIndexOutOfBoundsException
  • Depending on the requirements of the application, take necessary action. For example, log the exception with an appropriate message.
  • Check the length of the string using String.length() and access its characters that fall within the range.

The code in the earlier example can be updated with the above steps:

public class StringIndexOutOfBoundsExceptionExample {
    public static void main(String args[]) {
        String str = "My String";
        try {
            System.out.println(str.charAt(9));
        } catch(StringIndexOutOfBoundsException e) {
            System.out.println("String index out of bounds. String length: " + str.length());
        }
    }
}

Surrounding the code in try-catch blocks like the above allows the program to continue execution after the exception is encountered:

String index out of bounds. String length: 9

 

Track, Analyze and Manage Errors with Rollbar

Rollbar in action

Finding exceptions in your Java code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring, tracking and triaging, making fixing Java errors and exceptions easier than ever. Sign Up Today!

Related Posts

See all posts

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Start continuously improving your code today.

Get Started Shape