Java 中的 StringIndexOutOfBoundsException

2024 年 9 月 10 日 | 阅读 3 分钟

在 Java 中,StringIndexOutOfBoundsException 是一个运行时异常,当您尝试访问字符串中具有无效索引的字符时会抛出该异常。

尝试访问负数索引或超出字符串长度范围的索引会导致抛出此异常。

例如,如果有一个名为 myString 的字符串变量,其值为“Hello”,尝试访问 myString.charAt(5) 将导致 StringIndexOutOfBoundsException,因为索引 5 超出了范围(该字符串的有效索引为 0 到 4)。

您可以使用 try-catch 块来处理此异常。catch 块然后可以处理该异常并向用户提供适当的错误消息。

导致 StringIndexOutOfBoundsException 的原因

在 Java 中,当使用无效指定参数时,有几种方法可能会抛出 StringIndexOutOfBoundsException。以下是一些示例:

  1. String 类的 charAt(int index) 方法:该方法使用字符串中指定的索引来返回字符。如果索引小于 0 或大于等于字符串的长度,则会抛出 StringIndexOutOfBoundsException。
  2. String 类的 substring(int beginIndex, int endIndex) 方法:该方法返回一个新字符串,该字符串是原始字符串的子字符串。如果 beginIndex 或 endIndex 参数小于 0 或大于字符串的长度,或者 beginIndex 大于 endIndex,则会抛出 StringIndexOutOfBoundsException。
  3. substring(int beginIndex):在 Java 中,String.substring(int beginIndex) 方法返回一个新字符串,该字符串是原始字符串的子字符串,从指定的 beginIndex 开始,一直到原始字符串的末尾。beginIndex 是包含的,这意味着 beginIndex 处的字符包含在返回的字符串中。
  4. valueOf(char[] data, int offset, int count):Java 的此方法通过从指定的字符数组 data 中提取子字符串来创建新字符串。子字符串从 offset 指定的索引开始,长度为 count。如果 offset 和 count 值超出范围,则会抛出 StringIndexOutOfBoundsException。
  5. subSequence(int beginIndex, int endIndex):这是 Java 中的一个方法,它返回一个新的 CharSequence,该 CharSequence 是原始 CharSequence 对象的子序列。子序列从 beginIndex 开始,一直到 endIndex -1 位置处的字符。返回的 CharSequence 与原始对象共享相同的底层字符序列。

StringIndexOutOfBoundsException 示例

文件名: StringIndexOutOfBoundsExceptionExample.java

输出

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 2, end 8, length 7
	at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3319)
at java.base/java.lang.String.substring(String.java:1874)
	at StringIndexOutOfBoundsExceptionExample.main(StringIndexOutOfBoundsExceptionExample.java:4)

说明:在此示例中,在字符串上调用了 substring() 方法,指定的 beginIndex 为 2,endIndex 为 8,这超出了范围,因为字符串的长度只有 7(索引范围从 0 到 6)。因此,substring() 方法抛出了 StringIndexOutOfBoundsException。

处理 StringIndexOutOfBoundsException

由于 StringIndexOutOfBoundsException 是一个 Java 异常,可以使用以下步骤通过 try-catch 块来处理它:

  • 将 try-catch 块放在可能导致 StringIndexOutOfBoundsException 的任何语句周围。
  • 捕获 StringIndexOutOfBoundsException。

文件名: StringIndexOutOfBoundsExceptionExample.java

输出

String index is out of bounds: begin 2, end 8, length 7

说明:在此示例中,在字符串上调用了 substring() 方法,指定的索引为 2 和 8,这两个索引都超出了范围。执行 try 块中的代码,当抛出 StringIndexOutOfBoundsException 时,它被 catch 块捕获。在 catch 块中,将错误消息记录到控制台。

根据应用程序的要求,您可以在 catch 块中执行不同的操作,例如设置子字符串的默认值或提示用户输入有效的索引。