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`.
}
因为ArrayIndexOutOfBoundsException
是IndexOutOfBoundsException
的子类型 。
That is where Inheritance comes into picture, and helps to keep levels of Inheritance clean and focused, with main goal of extensibility. There cane be wrong Indexes not only in Array but even in String etc. HTH
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.