not that familiar with JAVA or exception handling. Looking for some advice on what is acceptable and what is frowned upon.
The scenario, i'm building a game of life program, I have conditionals set up to check if a cell will be out of bounds and not try to access that 'cell'. My question is, is it acceptable to use a try catch block instead of 8 conditionals, and just do nothing if the arrayOutOfBounds exception is thrown. ie ignore the cells out of bounds, or is this bad practice? for instance...
try{
neighbors += cellIsAlive(row, col);
}catch(ArrayIndexOutofBoundsException e)
{
//dont do anything and continue counting neighbors
}
In this scenario cellIsAlive method checks a location in a multi dimensional array and returns 1 if it's alive 0 otherwise and throws ArrayIndexOutofBoundsException.
Is this a good idea or is it bad practice to use exceptions this way?
Thanks ahead of time for any input.
It's absolutely a bad practice. Exception handling consumes a lot of resources and should be used only (as its name implies) for exceptional cases.
Take a look at chapter 9 of this book (and also read the rest when you can):
http://www.amazon.com/Effective-Java-Edition-Joshua-Bloch/dp/0321356683/
You'll see that what you're trying to do is very similar to the example used for illustrating what you're not supposed to do, and I quote:
Someday, if you are unlucky, you may stumble across a piece of code that looks something like this:
// Horrible abuse of exceptions. Don't ever do this!
try {
int i = 0;
while(true)
range[i++].climb();
} catch(ArrayIndexOutOfBoundsException e) {
}
What does this code do? It’s not at all obvious from inspection, and that’s reason enough not to use it (Item 55). It turns out to be a horribly ill-conceived idiom for looping through the elements of an array.
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