Ciò è inteso a mantenere una gerarchia che abbia senso e serve anche a raggruppare le relative eccezioni.
Inoltre, se si sa cos'è un IndexOutOfBoundsException
e qualcuno ti dà un'altra eccezione che estende questo, puoi immediatamente raccogliere informazioni da questo solo fatto. In questo caso, alcuni degli oggetti coinvolti mantengono gli indici all'interno di un certo intervallo.
Se ogni eccezione estesa Exception
o RuntimeException
(se la sua occorrenza deve essere controllata o non controllata) e il suo nome era alquanto oscuro, non avresti idea di cosa potrebbe rappresentare.
Considerare il seguente codice.
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`.
}