java
runtime_error
ai_generated
true
java.lang.StringIndexOutOfBoundsException: 字符串索引超出范围: ...
java.lang.StringIndexOutOfBoundsException: String index out of range: ...
ID: java/stringindexoutofboundsexception
92%修复率
87%置信度
1证据数
2023-04-05首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Java 8 | active | — | — | — |
| Java 11 | active | — | — | — |
| Java 17 | active | — | — | — |
| Java 21 | active | — | — | — |
根因分析
在字符串中访问索引为负数或大于等于字符串长度的字符。
English
Accessing a character in a string at an index that is negative or greater than or equal to the string length.
官方文档
https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/StringIndexOutOfBoundsException.html解决方案
-
Always check string length before accessing: 'if (index >= 0 && index < str.length()) { char c = str.charAt(index); }' -
Use safe substring with bounds clamping: 'int safeEnd = Math.min(end, str.length()); String sub = str.substring(start, safeEnd);'
无效尝试
常见但无效的做法:
-
90% 失败
Using String.charAt() without checking length first leads to this exception when the string is shorter than expected.
-
85% 失败
Assuming substring(start, end) works with end > length will throw this exception.