java
runtime_error
ai_generated
true
java.lang.StringIndexOutOfBoundsException: 字符串索引超出范围: 10
java.lang.StringIndexOutOfBoundsException: String index out of range: 10
ID: java/string-index-out-of-bounds-exception
88%修复率
83%置信度
1证据数
2023-12-01首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Java 8 | active | — | — | — |
| Java 11 | active | — | — | — |
| Java 17 | active | — | — | — |
| Java 21 | active | — | — | — |
根因分析
尝试使用负数或大于等于字符串长度的索引访问字符串中的字符,通常由差一错误或格式错误的输入引起。
English
An attempt to access a character in a String using an index that is negative or greater than or equal to the string length, often due to off-by-one errors or malformed input.
官方文档
https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/StringIndexOutOfBoundsException.html解决方案
-
Check the string length before accessing: if (index >= 0 && index < str.length()) { char c = str.charAt(index); } else { /* handle error */ } -
Use str.substring(start, end) with bounds checking, or use str.charAt(Math.min(index, str.length()-1)) as a temporary clamp.
无效尝试
常见但无效的做法:
-
70% 失败
This hides the bug and may cause downstream issues like null pointer exceptions or incorrect data processing.
-
85% 失败
This does not address the root cause of incorrect index calculation; the index may still be out of range for other inputs.