如何在 Java 中处理 StringIndexOutOfBoundsException?

java 8object oriented programmingprogramming更新于 2025/4/26 21:22:17

Java 中,字符串用于存储字符序列,它们被视为对象。java.lang 包中的 String 类表示一个字符串。

您可以使用 new 关键字(像任何其他对象一样)或通过为字面量赋值(像任何其他原始数据类型一样)来创建字符串。

示例

public class StringDemo {
   public static void main(String args[]) {
      String stringObject = new String("Hello how are you");
      System.out.println(stringObject);
      String stringLiteral = "Welcome to Tutorialspoint";
      System.out.println(stringLiteral);
   }
}

输出

Hello how are you
Welcome to Tutorialspoint

数组中的索引

数组是一种数据结构/容器/对象,用于存储固定大小的、连续的同类型元素集合。数组的大小/长度在创建时确定。

元素在数组中的位置称为索引或下标。数组的第一个元素存储在索引 0 处,第二个元素存储在索引 1 处,依此类推。

字符串中的索引

由于字符串存储的是字符数组,因此与数组一样,每个字符的位置都由索引(从 0 开始)表示。例如,如果我们创建了一个字符串,其值为 −

String str = "Hello";

其中的字符定位为 −

StringIndexOutOfBoundsException

如果您尝试访问字符串中索引处大于其长度的字符,则会抛出 StringIndexOutOfBoundsException  异常。

示例

Java 中的 String 类提供了多种操作字符串的方法。您可以使用此类的 charAt() 方法查找特定索引处的字符。

此方法接受一个指定字符串索引的整数值,并返回字符串中指定索引处的字符。

在下面的 Java 程序中,我们创建一个长度为 17 的字符串,并尝试打印索引为 40 的元素。

public class Test {
   public static void main(String[] args) {
      String str = "Hello how are you";
      System.out.println("Length of the String: "+str.length());
      for(int i=0; i<str.length(); i++) {
         System.out.println(str.charAt(i));
      }
      //访问大于字符串长度的元素
      System.out.println(str.charAt(40));
   }
}

运行时异常

由于我们访问的元素索引大于其长度,因此抛出了 StringIndexOutOfBoundsException。

Length of the String: 17
H
e
l
l
o

h
o
w

a
r
e

y
o
u
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 40
   at java.base/java.lang.StringLatin1.charAt(Unknown Source)
   at java.base/java.lang.String.charAt(Unknown Source)
   at Test.main(Test.java:9)

处理 StringIndexOutOfBoundsException 异常

与其他异常一样,您可以通过将容易发生此异常的代码包装在 try catch 中来处理此异常。在 catch 块中捕获类型为 IndexOutOfBoundsException 或 StringIndexOutOfBoundsException 的异常。

public class Test {
   public static void main(String[] args) {
      String str = "Hello how are you";
      for(int i=0; i<tr.length(); i++) {
         System.out.println(str.charAt(i));
      }
      System.out.println(str.length());
      //访问大于字符串长度的元素
      try {
         System.out.println(str.charAt(40));
      }catch(StringIndexOutOfBoundsException e) {
         System.out.println("Exception occurred . . . . . . . . ");
      }
   }
}

输出

H
e
l
l
o

h
o
w

a
r
e

y
o
u
17
Exception occurred . . . . . . . .

相关文章