Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why java ArrayIndexOutOfBound Exception Extends IndexOutofBound Exception not Throwable?

I have a doubt in Exception with Inheritance.

why

public class ArrayIndexOutOfBoundsException extends IndexOutOfBoundsException

and then

public class IndexOutOfBoundsException extends RuntimeException

and then

public class RuntimeException extends Exception

Why Not

public class ArrayIndexOutOfBoundsException extends Exception

Why this hierarchy is maintained.. Any guidance will be helpful?

like image 889
Amith Avatar asked Oct 16 '13 08:10

Amith


2 Answers

That's because ArrayIndexOutOfBoundsException is also a IndexOutOfBoundsException, and RuntimeException.

In your suggestion, ArrayIndexOutOfBoundsException will only be Exception.

So if you want to catch only RuntimeException for example, ArrayIndexOutOfBoundsException won't be caught.

like image 130
BobTheBuilder Avatar answered Oct 02 '22 12:10

BobTheBuilder


That is intended to keep an hierarchy that makes sense, and also serves to group related exceptions.

Also, if you know what an IndexOutOfBoundsException is, and someone gives you another exception that extends this one, you can immediately gather information from this fact alone. In this case, that some of the involved objects keep indexes within a certain range.

If every exception extended Exception or RuntimeException (whether its occurrence should be checked or non-checked), and its name was somewhat obscure, you'd have no clue as to what it might represent.

Consider the following code.

try {
    for (int i = 0; i < limit; ++i) {
        myCharArray[i] = myString.charAt(i);
    }
}
catch (StringIndexOutOfBoundsException ex) {
    // Do you need to treat string indexes differently?
}
catch (ArrayIndexOutOfBoundsException ex) {
    // Perhaps you need to do something else when the problem is the array.
}
catch (IndexOutOfBoundsException ex) {
    // Or maybe they can both be treated equally.
    // Note: you'd have to remove the previous two `catch`.
}
like image 30
afsantos Avatar answered Oct 02 '22 11:10

afsantos