How to handle the StringIndexOutOfBoundsException (unchecked) in Java?

JavaObject Oriented ProgrammingProgramming

The StringIndexOutOfBoundsException is one of the unchecked exceptions in Java. A string is kind of an ensemble of characters. String object has a range of [0, length of the string]. When someone tries to access the characters with limits exceeding the range of actual string value, this exception occurs.

Example1

Live Demo

public class StringDemo {
   public static void main(String[] args) {
      String str = "Welcome to Tutorials Point.";
      System.out.println("Length of the String is: " + str.length());
      System.out.println("Length of the substring is: " + str.substring(28));
   }
}

Output

Length of the String is: 27
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
       at java.lang.String.substring(String.java:1931)
       at StringDemo.main(StringDemo.java:6)


How to handle the StringIndexOutOfBoundsException

  • We can check the range of the string using String.length() method and proceed to access the characters of it accordingly.
  • We can use try and catch block around the code snippet that can possibly throw StringIndexOutOfBoundsException.

Example2

Live Demo

public class StringIndexOutOfBoundsExceptionTest {
   public static void main(String[] args) {
      String str = "Welcome to Tutorials Point.";
      try {
        // StringIndexOutOfBoundsException will be thrown because str only has a length of 27.
str.charAt(28);
         System.out.println("String Index is valid");
      } catch (StringIndexOutOfBoundsException e) {
         System.out.println("String Index is out of bounds");
      }
   }
}

Output

String Index is out of bounds
raja
Published on 27-Jun-2019 10:39:32
Advertisements