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

这篇博客探讨了Java中常见的`StringIndexOutOfBoundsException`异常,详细解释了该异常的触发原因,包括字符串操作如substring()时下标越界的情况。文章通过一个具体的代码示例展示了如何引发并修复这个问题,并提供了异常的源码分析,帮助开发者更好地理解和预防此类错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Archie_java

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值