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

x33g5p2x  于2022-05-19 转载在 Java  
字(1.5k)|赞(0)|评价(0)|浏览(565)

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

字符串截取下标越界

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

出错代码

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

StringIndexOutOfBoundsException 异常源码如下:

/**
 * Thrown by {@code String} methods to indicate that an index
 * is either negative or greater than the size of the string.  For
 * some methods such as the charAt method, this exception also is
 * thrown when the index is equal to the size of the string.
 */
public
class StringIndexOutOfBoundsException extends IndexOutOfBoundsException {
    private static final long serialVersionUID = -6762910422159637258L;
 
    /**
     * Constructs a {@code StringIndexOutOfBoundsException} with no
     * detail message.
     *
     * @since   JDK1.0.
     */
    public StringIndexOutOfBoundsException() {
        super();
    }
 
    /**
     * Constructs a {@code StringIndexOutOfBoundsException} with
     * the specified detail message.
     *
     * @param   s   the detail message.
     */
    public StringIndexOutOfBoundsException(String s) {
        super(s);
    }
 
    /**
     * Constructs a new {@code StringIndexOutOfBoundsException}
     * class with an argument indicating the illegal index.
     *
     * @param   index   the illegal index.
     */
    public StringIndexOutOfBoundsException(int index) {
        super("String index out of range: " + index);
    }
}

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

String.substring()

String.charAt()

String.codePointAt()

String.codePointBefore()

String.subSequence()

String.getChars()

String.getBytes()

相关文章

微信公众号

最新文章

更多