Blog About Contact

Java String "substring" - an example of lazy error messages...

Published Sun, 19 Sep 2010 • 2 comments

What does this error mean?

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1

That's easy right? You've passed "-1" as an argument to a Java String's "substring" method.

Wrong.

Here's some code that gives the same error -

"fred smith".substring(4, 3);
See the bug? The start index is after the end index (by 1 character). To me, this is pretty poor API design. Neither of the arguments are out of bounds of the String's length, so why raise a StringIndexOutOfBoundsException? Worse, the index reported is neither of the indices passed. And finally, the exact same error message is reported for another common mistake, e.g.
"fred smith".substring(-1, 3)
Here's the offending code in Java's core String.java -
    public String substring(int beginIndex, int endIndex) {
    if (beginIndex < 0) {
        throw new StringIndexOutOfBoundsException(beginIndex);
    }
    if (endIndex > count) {
        throw new StringIndexOutOfBoundsException(endIndex);
    }
    if (beginIndex > endIndex) {
        throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
    }
    return ((beginIndex == 0) && (endIndex == count)) ? this :
        new String(offset + beginIndex, endIndex - beginIndex, value);
    }

For what it's worth, this should probably be an IllegalArgumentException, since the argument's have nothing to do with being out of bounds of the string and are just illegal with respect to one another. This would also allow for a meaningful error message such as "Start index (4) is before end index (3)".

It's funny the stuff you find when fixing gnarly bugs :)


About the Author

Richard Nichols is an Australian software engineer with a passion for making things.

Follow him on twitter or subscribe by RSS or email.

You might also enjoy reading -


Discuss / Comment

There are 2 comments.

Add a comment

  • {{e.error}}

Thanks for your comment!/

Required.
Valid email address required.
Required.
Posting message, please wait...