# java.lang.StringIndexOutOfBoundsException: 字符串索引超出范围: ...

- **ID:** `java/stringindexoutofboundsexception`
- **领域:** java
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 92%

## 根因

在字符串中访问索引为负数或大于等于字符串长度的字符。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Java 8 | active | — | — |
| Java 11 | active | — | — |
| Java 17 | active | — | — |
| Java 21 | active | — | — |

## 解决方案

1. ```
   Always check string length before accessing: 'if (index >= 0 && index < str.length()) { char c = str.charAt(index); }'
   ```
2. ```
   Use safe substring with bounds clamping: 'int safeEnd = Math.min(end, str.length()); String sub = str.substring(start, safeEnd);'
   ```

## 无效尝试

- **** — Using String.charAt() without checking length first leads to this exception when the string is shorter than expected. (90% 失败率)
- **** — Assuming substring(start, end) works with end > length will throw this exception. (85% 失败率)
