

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to handle the StringIndexOutOfBoundsException (unchecked) in Java?
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
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
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
- Related Questions & Answers
- How to handle StringIndexOutOfBoundsException in Java?
- How to handle the ArithmeticException (unchecked) in Java?
- How to handle the NumberFormatException (unchecked) in Java?
- How to handle the ArrayStoreException (unchecked) in Java?
- What is StringIndexOutOfBoundsException in Java?
- How to create a custom unchecked exception in Java?
- How to handle the Runtime Exception in Java?
- How to handle MalformedURLException in java?
- How to handle EOFException in java?
- What are unchecked exceptions in Java?
- Checked vs Unchecked exceptions in Java
- How to handle the exception using UncaughtExceptionHandler in Java?
- How to handle Assertion Error in Java?
- Checked Vs unchecked exceptions in Java programming.
- How to handle proxy in Selenium in Java?
Advertisements