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?
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.
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`.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With