Checking out of bounds in Java

lemon picture lemon · Oct 30, 2013 · Viewed 57.5k times · Source

I'm trying to check if an array location is out of bounds, what's the simplest way?

int[] arr;
populate(arr);
if(arr[-1] == null)
//out of bounds!

Would something like this work?

I'm pretty sure this can be done with a trycatch or a scanner but for just a simple small program, is there another way?

Answer

arshajii picture arshajii · Oct 30, 2013

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.