Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java dealing with exceptions appropriately

Tags:

java

exception

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.

like image 879
Bryan Avatar asked Feb 14 '23 17:02

Bryan


1 Answers

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.

like image 73
Andres Avatar answered Feb 20 '23 11:02

Andres