java runtime_error ai_generated true

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

java.lang.StringIndexOutOfBoundsException: String index out of range: ...

ID: java/stringindexoutofboundsexception

其他格式: JSON · Markdown 中文 · English
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.

generic

官方文档

https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/StringIndexOutOfBoundsException.html

解决方案

  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);'

无效尝试

常见但无效的做法:

  1. 90% 失败

    Using String.charAt() without checking length first leads to this exception when the string is shorter than expected.

  2. 85% 失败

    Assuming substring(start, end) works with end > length will throw this exception.