如何处理 Java 中的 StringIndexOutOfBoundsException(未检查)?
javaobject oriented programmingprogramming
StringIndexOutOfBoundsException 是 Java 中的 未检查异常 之一。字符串是字符的集合。String 对象 的范围为 [0,字符串长度]。当有人尝试访问超出实际字符串值范围的字符时,就会发生此异常。
示例 1
public class StringDemo { public static void main(String[] args) { String str = "Welcome to Tutorials Point."; System.out.println("Length of the String is: " + str.length()); System.out.println("Length of the substring is: " + str.substring(28)); } }
输出
Length of the String is: 27 Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.String.substring(String.java:1931) at StringDemo.main(StringDemo.java:6)
如何处理 StringIndexOutOfBoundsException
- 我们可以使用 String.length() 方法检查字符串的范围,并继续相应地访问其字符。
- 我们可以使用 try and catch block 来处理可能抛出 StringIndexOutOfBoundsException 的代码片段。
示例2
public class StringIndexOutOfBoundsExceptionTest { public static void main(String[] args) { String str = "Welcome to Tutorials Point."; try { // StringIndexOutOfBoundsException will be thrown because str only has a length of 27. str.charAt(28); System.out.println("String Index is valid"); } catch (StringIndexOutOfBoundsException e) { System.out.println("String Index is out of bounds"); } } }
输出
String Index is out of bounds