Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

จัดการ StringIndexOutOfBoundsException (Unchecked) ใน Java

StringIndexOutOfBoundsException เป็น Unchecked Exception** เกิดเมื่อเข้าถึง Character ใน String ด้วย Index ที่ เกินช่วง [0, length-1]

ตัวอย่างที่ทำให้เกิด Exception


public class StringDemo {
    public static void main(String[] args) {
        String str = "Welcome to Tutorials Point.";
        System.out.println("Length: " + str.length());  // 27
        System.out.println(str.substring(28));           // ERROR! Index 28 >= Length
    }
}

ผลลัพธ์ (Exception)


Length: 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)

วิธีจัดการ (Handling)

1. ตรวจสอบ Range ก่อนเข้าถึง


String str = "Hello";
int index = 10;

if (index >= 0 && index < str.length()) {
    char c = str.charAt(index);  // Safe
} else {
    System.out.println("Index out of bounds");
}

2. Try-Catch Block


public class StringIndexOutOfBoundsExceptionTest {
    public static void main(String[] args) {
        String str = "Welcome to Tutorials Point.";
        
        try {
            char c = str.charAt(28);  // Index 28 ไม่มี (Length=27)
            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

เมธอดที่อาจโยน Exception นี้

  • charAt(int index)
  • substring(int begin, int end)
  • subSequence(int begin, int end)
  • getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
  • codePointAt(int index), codePointBefore(int index)

Best Practices

  • ใช้ str.length() เช็คก่อนเข้าถึง
  • ใช้ str.isEmpty() เช็ค String ว่าง
  • Try-Catch เฉพาะจุดที่อาจ Error (Don't catch broadly)
  • Logging Exception เพื่อ Debug
  • Input Validation ตอนรับข้อมูลจาก User/External

Java 9+ เพิ่มเติม


// Optional-style (ไม่ใช่ built-in แต่ Pattern ที่ดี)
public static Optional safeCharAt(String s, int index) {
    return (index >= 0 && index < s.length()) ? Optional.of(s.charAt(index)) : Optional.empty();
}