Absolutely do not use try-catch for this. Simply use:
boolean inBounds = (index >= 0) && (index < array.length);
Implementing the approach with try-catch would entail catching an ArrayIndexOutOfBoundsException
, which is an unchecked exception (i.e. a subclass of RuntimeException
). Such exceptions should never (or, at least, very rarely) be caught and dealt with. Instead, they should be prevented in the first place.
In other words, unchecked exceptions are exceptions that your program is not expected to recover from. Now, there can be exceptions (no pun intended) to this here and there. For instance, it has become common practice to check if a string is parable as an integer by calling Integer.parseInt()
on it and catching the potential NumberFormatException
(which is unchecked). This is considered OK, but always think twice before doing something like that.