StringIndexOutOfBoundsException अनियंत्रित . में से एक है अपवाद जावा में। एक स्ट्रिंग वर्णों का एक समूह है। स्ट्रिंग ऑब्जेक्ट इसकी श्रेणी . है [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() . का उपयोग करके स्ट्रिंग की श्रेणी की जांच कर सकते हैं विधि और तदनुसार इसके पात्रों तक पहुँचने के लिए आगे बढ़ें।
- हम उपयोग कर सकते हैं कोशिश करें और ब्लॉक को पकड़ें कोड स्निपेट के आसपास जो संभवतः StringIndexOutOfBoundsException throw फेंक सकता है ।
उदाहरण2
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");
}
}
} आउटपुट
String Index is out of bounds