Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 963
zds Avatar asked Oct 17 '25 17:10

zds


1 Answers

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
    }
}
like image 130
Eng.Fouad Avatar answered Oct 20 '25 07:10

Eng.Fouad