2

Let's take as reference the next code:

try{
   /*Code that may throw IndexOutOfBoundsException or ArrayIndexOut......*/
} catch (IndexOutOfBoundsException e){
    /*handle*/
} catch (ArrayIndexOutOfBoundsException e){
    /*handle*/
}
  • Why doesn't this compile, but if a switch the sequence of catch clauses it does compile?

  • Maybe I must first write a specific exception and then a more general?

lealceldeiro
  • 14,342
  • 6
  • 49
  • 80

2 Answers2

5

Because ArrayIndexOutOfBoundsException extends from IndexOutOfBoundsException, which means the first one is more specific than the second one.

So if there is an ArrayIndexOutOfBoundsException it is matched to an IndexOutOfBoundsException: in other words, the catch for ArrayIndexOutOfBoundsException would be unreachable.

For all exceptions declared in your catches to be reachable, you need to order them from the most specific to the most generic ones.

lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
2

Because ArrayIndexOutOfBoundsException is a subclass of IndexOutOfBoundsException, so the second clause is unreachable because the first one will always catch the exception.

steven35
  • 3,747
  • 3
  • 34
  • 48