StringIndexOutOfBoundsException আনচেক করা গুলির মধ্যে একটি৷ ব্যতিক্রম জাভাতে। একটি স্ট্রিং অক্ষর একটি ensemble ধরনের হয়. স্ট্রিং অবজেক্ট একটি পরিসীমা আছে [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 নিক্ষেপ করতে পারে .
উদাহরণ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