Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách xử lý StringIndexOutOfBoundsException (unchecked) trong Java

StringIndexOutOfBoundsException là một trong các unchecked exceptions trong Java. String là tập hợp ký tự. String object có phạm vi chỉ số [0, length - 1]. Khi truy cập ký tự vượt quá phạm vi thực tế, ngoại lệ này xảy ra.

Ví dụ gây ra ngoại lệ

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()); // 27 
        System.out.println("Length of the substring is: " + str.substring(28)); // LỖI 
    } 
}

Kết quả

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)

Cách xử lý StringIndexOutOfBoundsException

  1. Kiểm tra phạm vi trước dùng String.length().
  2. Dùng try-catch bao quanh code có thể ném ngoại lệ.

Ví dụ xử lý bằng try-catch

public class StringIndexOutOfBoundsExceptionTest { 
    public static void main(String[] args) { 
        String str = "Welcome to Tutorials Point."; 
        try { 
            // StringIndexOutOfBoundsException sẽ ném vì str chỉ length 27 
            str.charAt(28); 
            System.out.println("String Index is valid"); 
        } catch (StringIndexOutOfBoundsException e) { 
            System.out.println("String Index is out of bounds"); 
        } 
    } 
}

Kết quả

String Index is out of bounds

Best Practices

  • Luôn kiểm tra index >= 0 && index < str.length() trước khi dùng charAt(), substring().
  • Dùng str.length() làm upper bound, không hardcode số.
  • Ưu tiên substring(begin, end) với end = Math.min(end, str.length()).
  • Java 9+: String.strip(), isBlank() giúp tránh lỗi index trên chuỗi rỗng/khoảng trắng.