Java corresponding exceptions

not familiar with JAVA or exception handling. Look for some advice on what is acceptable and what you frowned at.

The scenario, I am building a game of the life program, I have conditions set for checking whether a cell will be outside the borders and not trying to access this cell. My question is: is it acceptable to use a catch try block instead of 8 conditional expressions and just do nothing if an arrayOutOfBounds exception is thrown. those. ignore cells outside borders, or is it bad practice? eg...

try{
    neighbors += cellIsAlive(row, col);
}catch(ArrayIndexOutofBoundsException e)
{
    //dont do anything and continue counting neighbors
}

In this case, the cellIsAlive method checks the location in a multidimensional array and returns 1 if it is alive 0, and throws an ArrayIndexOutofBoundsException.

Is it a good idea or bad practice to use exceptions this way?

Thanks for any input.

+4
source share
3 answers

This is absolutely bad practice. Exception handling consumes a lot of resources and should only be used (as the 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 will see that what you are trying to do is very similar to the example used to illustrate what you should not do, and I will quote:

Someday, if you're out of luck, you might stumble upon 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) {
}

? , ( 55). , .

+5

, RuntimeExcepions. ArrayIndexOutofBoundsException RuntimeException. RuntimeExceptions , .

+3

Catching ArrayIndexOutofBoundsException - . cellIsActive().

http://www.tutorialspoint.com/java/java_exceptions.htm

0

Source: https://habr.com/ru/post/1527845/


All Articles