的相关代码substring
为:
1965 int subLen = endIndex - beginIndex;
1966 if (subLen < 0) {
1967 throw new StringIndexOutOfBoundsException(subLen);
1968 }
如果您-4
在异常消息中看到,这意味着endIndex - beginIndex == -4
.
显然,endIndex
应该大于或等于beginIndex
,这样差异就不会是负数。
查看完整的方法(此版本的代码似乎与您的版本相匹配,基于行号 - 1967 - 其中引发了异常):
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > value.length) {
throw new StringIndexOutOfBoundsException(endIndex);
}
int subLen = endIndex - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return ((beginIndex == 0) && (endIndex == value.length)) ? this
: new String(value, beginIndex, subLen);
}
您可以看到如果是,您会收到-1
错误消息。beginIndex
-1
但是如果beginIndex
是非负数并且endIndex
不是太大,那么您在异常消息中得到的数字是endIndex - beginIndex
.