zds zds - 2 months ago 8
Java Question

EAFP. Ask for forgiveness not permission in Java

Is it a good practice in Java to ask for forgiveness not permission in general and in the next example?

The example is:

try {
Cell value = array2D[rowIndex][columnIndex];
}
catch (ArrayIndexOutOfBoundsException e) {}


As you can see in the above piece of code we get
value
out of the
array2D
. If the
value
is out of bounds we do nothing.

I ask this question because it is much easier to implement
EAFP
than
LBYL
(look before you leap) in some cases (for example finding all neighbors of given
Cell
in
array2D
).

Answer

You can avoid the overhead of throwing an exception by checking the size of the array:

if(rowIndex < array2D.length)
{
    if(columnIndex < array2D[rowIndex].length)
    {
        // you are safe here
    }
}