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
).
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With