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

小鱼儿 2023-09-30 13:39 22阅读 0赞

[2022 中国 DevOps 现状调查全面启动!>>>

字符串截取下标越界

  1. java.lang.StringIndexOutOfBoundsException: String index out of range: -1
  2. at java.lang.String.substring(String.java:1967)

出错代码

  1. result.put("value", valueBuilder.toString().substring(0,valueBuilder.toString().length()-1));
修改后代码
  1. if (StringUtils.isNotBlank(valueBuilder.toString()) && valueBuilder.toString().length() >0){
  2. result.put("value", valueBuilder.toString().substring(0,valueBuilder.toString().length()-1));
  3. }
总结

StringIndexOutOfBoundsException 异常源码如下:

  1. /**
  2. * Thrown by {@code String} methods to indicate that an index
  3. * is either negative or greater than the size of the string. For
  4. * some methods such as the charAt method, this exception also is
  5. * thrown when the index is equal to the size of the string.
  6. */
  7. public
  8. class StringIndexOutOfBoundsException extends IndexOutOfBoundsException {
  9. private static final long serialVersionUID = -6762910422159637258L;
  10. /**
  11. * Constructs a {@code StringIndexOutOfBoundsException} with no
  12. * detail message.
  13. *
  14. * @since JDK1.0.
  15. */
  16. public StringIndexOutOfBoundsException() {
  17. super();
  18. }
  19. /**
  20. * Constructs a {@code StringIndexOutOfBoundsException} with
  21. * the specified detail message.
  22. *
  23. * @param s the detail message.
  24. */
  25. public StringIndexOutOfBoundsException(String s) {
  26. super(s);
  27. }
  28. /**
  29. * Constructs a new {@code StringIndexOutOfBoundsException}
  30. * class with an argument indicating the illegal index.
  31. *
  32. * @param index the illegal index.
  33. */
  34. public StringIndexOutOfBoundsException(int index) {
  35. super("String index out of range: " + index);
  36. }
  37. }

总共有以下几个方法会抛出该异常:

  1. String.substring()
  2. String.charAt()
  3. String.codePointAt()
  4. String.codePointBefore()
  5. String.subSequence()
  6. String.getChars()
  7. String.getBytes()

发表评论

表情:
评论列表 (有 0 条评论,22人围观)

还没有评论,来说两句吧...

相关阅读

    相关 String index out of range: -1

          前两天报字符串越界,查找中发现,应该是取某一个字符的位置时,出错了,原来使用lastIndexOf时要取得这个字符在被查找的字符串里没有。 解决方法,在取位置之前