StringIndexOutOfBoundsException Java में अनचेक्ड एक्सेप्शन्स में से एक है। एक स्ट्रिंग कैरेक्टर्स का एक समूह है। String ऑब्जेक्ट की रेंज [0, स्ट्रिंग की लंबाई] होती है। जब कोई वास्तविक स्ट्रिंग वैल्यू की रेंज से अधिक सीमाओं के साथ कैरेक्टर्स को एक्सेस करने का प्रयास करता है, तो यह एक्सेप्शन होता है।
उदाहरण 1
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));
}
}
आउटपुट
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)
StringIndexOutOfBoundsException को कैसे हैंडल करें
- हम String.length() मेथड का उपयोग करके स्ट्रिंग की रेंज चेक कर सकते हैं और तदनुसार इसके कैरेक्टर्स को एक्सेस कर सकते हैं।
- हम उस कोड स्निपेट के चारों ओर try और catch ब्लॉक का उपयोग कर सकते हैं जो संभावित रूप से StringIndexOutOfBoundsException थ्रो कर सकता है।
उदाहरण 2
public class StringIndexOutOfBoundsExceptionTest {
public static void main(String[] args) {
String str = "Welcome to Tutorials Point.";
try {
// StringIndexOutOfBoundsException थ्रो होगा क्योंकि str की केवल लंबाई 27 है।
str.charAt(28);
System.out.println("String Index is valid");
} catch (StringIndexOutOfBoundsException e) {
System.out.println("String Index is out of bounds");
}
}
}
आउटपुट
String Index is out of bounds
हमेशा स्ट्रिंग लंबाई चेक करें या try-catch का उपयोग करें जब इंडेक्स डायनामिक हो।