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 .
ตัวอย่าง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