StringIndexOutOfBoundsException জাভাতে অনচেকড এক্সেপশন-এর একটি। একটি স্ট্রিং ক্যারেক্টারগুলোর একটি সমষ্টি। String অবজেক্ট-এর একটি রেঞ্জ থাকে [0, স্ট্রিং-এর দৈর্ঘ্য]। কেউ যখন আসলে স্ট্রিং মানের রেঞ্জের বাইরে ক্যারেক্টার এক্সেস করার চেষ্টা করে, তখন এই এক্সেপশন ঘটে।
উদাহরণ ১
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() মেথড ব্যবহার করে স্ট্রিং-এর রেঞ্জ চেক করে megfelelően ক্যারেক্টার এক্সেস করুন।
- যে কোড স্নিপেটটি StringIndexOutOfBoundsException থ্রো করতে পারে, সেটির চারপাশে try এবং catch ব্লক ব্যবহার করুন।
উদাহরণ ২
public class StringIndexOutOfBoundsExceptionTest {
public static void main(String[] args) {
String str = "Welcome to Tutorials Point.";
try {
// StringIndexOutOfBoundsException থ্রো হবে কারণ str-এর শুধু length 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