该的StringIndexOutOfBoundsException 是一个未经检查的 异常 在Java中。字符串是一种字符集合。字符串 对象 的范围为 [0,字符串的长度]。当有人尝试访问超出实际字符串值范围的限制的字符时,会发生此异常。
public class StringDemo {
public static void main(String[] args) {
String str = "Welcome to (niaoge.com).";
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)
我们可以使用String.length() 方法检查字符串的范围,然后相应地访问它的字符。
我们可以在代码片段周围使用try and catch块 ,它可能会抛出StringIndexOutOfBoundsException。
public class StringIndexOutOfBoundsExceptionTest {
public static void main(String[] args) {
String str = "Welcome to (niaoge.com).";
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