简体   繁体   中英

IndexOutOfBounds Exception Java String Class charAt Method

Method CharAt of the Java String class throws a StringIndexOutOfBoundsException. But the Java API documentation says it throws an IndexOutOfBoundsException . I know that StringIndexOutOfBoundsException is a subclass of IndexOutOfBoundsException . But is it incorrect to catch StringIndexOutOfBoundsException instead of IndexOutOfBoundsException ?

Here is the code of the charAt method

public char charAt(int index) {
        if ((index < 0) || (index >= value.length)) {
            throw new StringIndexOutOfBoundsException(index);
        }
        return value[index];
    }

No, it's not incorrect. But you can save a few keystrokes and just use IndexOutOfBoundsException, unless you have a method that uses String indexing and eg array indexing or list indexing etc. Then you could differentiate the exception types to handle the cases differently.

It is just the closest exception thrown , what is the need of having so many inbuilt Exception classes, when we can always throw/use Exception class .

You have ArrayIndexOutOfBoundsException for Arrays, similarly StringIndexOutOfBoundsException for working on Strings etc..

more here

I would prefer IndexOutOfBoundsException in situations like this :

 public static void main(String[] args) {
    String s = "abc";
    String[] arr = new String[1];
    for (int i = 0; i < 2; i++) {
        try {
            s.charAt(5);
            System.out.println(arr[2]);
        } catch (IndexOutOfBoundsException e) { // catch both ArrayIndexOutOfBounds as well as StringIndexOutOfBounds and treat them similarly.
            System.out.println("caught");
            s = "aaaaaaaaaa";
            e.printStackTrace();

        }
    }

}

O/P :
0
java.lang.StringIndexOutOfBoundsException: String index out of range: 5
caught
caught
    at java.lang.String.charAt(Unknown Source)
    at StaticAssign.main(Sample.java:41)
java.lang.ArrayIndexOutOfBoundsException: 2
    at StaticAssign.main(Sample.java:42)

It is not wrong. It is just a design consideration. The same applies to IOException and FileNotFoundException .

You should not look at a specific implementation. The documentation says it throws IndexOutOfBoundsException , then if you want to handle this (which is not really necessary) you'd better catch that.

There could be different Java implementations that don't do the check and simply let the array access throw ArrayIndexOutOfBoundsException , or in the next version Oracle might decide to do that.

Just handling StringIndexOutOfBoundsException would couple you to a specific implementation, and not to the general contract described in the API documentation.

My example above is purely hypothetical, as the documentation of StringIndexOutOfBoundsException firmly establishes that String should throw it, but as a general rule: follow the contract.

It's not incorrect since that's what the method actually throws, and since it's a RuntimeException (ie unchecked), it doesn't matter, since you don't have to catch it at all.

Now, if it was a checked exception :

public char someMethod (int index) throws SomeCheckedException {
    if (index < 0) {
        throw new SomeSubCheckedException (index); // subclass of SomeCheckedException 
    }
    return something;
}

Here, if you call someMethod in a try block and only catch SomeSubCheckedException , the code won't pass compilation, since, as far as the compiler is concerned, someMethod may throw an instance of SomeCheckedException which is not SomeSubCheckedException .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM