由String index out of range: -1引发的思考
废话不多说,这个错误很容易就能明白其含义:字符串的索引越界了。
一般都是字符串操作引起的,最典型的:
String str = “123456789”;//字符串长度是9
String tempStr = str.substring(0, 10);//一定报错:String index out of range: 10
该错误是由于字符串操作过程中抛出StringIndexOutOfBoundsException异常,源码如下:
package java.lang;
/**
* Thrown by {@code String} methods to indicate that an index
* is either negative or greater than the size of the string. For
* some methods such as the charAt method, this exception also is
* thrown when the index is equal to the size of the string.
*
* @author unascribed
* @see java.lang.String#charAt(int)
* @since JDK1.0
*/
public
class StringIndexOutOfBoundsException extends IndexOutOfBoundsException {
private static final long serialVersionUID = -6762910422159637258L;
/**
* Constructs a {@code StringIndexOutOfBoundsException} with no
* detail message.
*
* @since JDK1.0.
*/
public StringIndexOutOfBoundsException() {
super();
}
/**
* Constructs a {@code StringIndexOutOfBoundsException} with
* the specified detail message.
*
* @param s the detail message.
*/
public StringIndexOutOfBoundsException(String s) {
super(s);
}
/**
* Constructs a new {@code StringIndexOutOfBoundsException}
* class with an argument indicating the illegal index.
*
* @param index the illegal index.
*/
public StringIndexOutOfBoundsException(int index) {
super("String index out of range: " + index);
}
}
最后,总结一下,总共有以下几个方法会抛出该异常:
String.substring()
String.charAt()
String.codePointAt()
String.codePointBefore()
String.subSequence()
String.getChars()
String.getBytes()