由String index out of range: -1引发的思考

本文详细解释了StringIndexOutOfBoundsException异常产生的原因及其在Java中常见的几种触发场景,如使用String.substring等方法时的操作不当。

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

String index out of range: -1引发的思考

废话不多说,这个错误很容易就能明白其含义:字符串的索引越界了。

一般都是字符串操作引起的,最典型的:

String str = “123456789”;//字符串长度是9
String tempStr = str.substring(0, 10);//一定报错:String index out of range: 10

该错误是由于字符串操作过程中抛出StringIndexOutOfBoundsException异常,源码如下:

package java.lang;

/**
 * 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.
 *
 * @author  unascribed
 * @see     java.lang.String#charAt(int)
 * @since   JDK1.0
 */
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()

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

长乐smile

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

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

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

打赏作者

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

抵扣说明:

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

余额充值