Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

IndexOutOfBounds and StringIndexOutOfBounds  RSS feed

Sarma Lolla
Ranch Hand
Posts: 203
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is what API documentations about String.subString method

public String substring(int beginIndex,
int endIndex)Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.
"hamburger".substring(4, 8) returns "urge"
"smiles".substring(1, 5) returns "mile"

beginIndex - the beginning index, inclusive.
endIndex - the ending index, exclusive.
the specified substring.

IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.

Here again API documentation about StringIndexOutOfBoundsException

public class StringIndexOutOfBoundsException
extends IndexOutOfBoundsException
Thrown by 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.

My question is Can there be any confusion when dealing with questions on Strings in exam?
When I execute a simple subString() with negative index for the end index I am getting StringIndexOutOfBounds instead of IndexOutOfBounds as specified by API.
[ March 03, 2003: Message edited by: Sarma Lolla ]
Rodney Woodruff
Ranch Hand
Posts: 80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This can be confusing. Keep in mind that StringIndexOutOfBoundsException extends IndexOutOfBoundsException. This means that StringIndexOutOfBoundsException is an IndexOutOfBoundsException.
So, to more directly answer your question, it helps to understand in the inheritance hierarchy.
For example:

would work if the code that generated the exception threw either StringIndexOutOfBoundsException or an IndexOutOfBoundsException. However, the following code:

would only catch a StringIndexOutOfBoundsException.
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!