Java dealing with exceptions appropriately

半城伤御伤魂 提交于 2019-12-19 09:17:20

问题


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.


回答1:


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.




回答2:


It's a bad practice to catch RuntimeExcepions. ArrayIndexOutofBoundsException is a subclass of RuntimeException. RuntimeExceptions are programmers fault, You should catch only checked Exceptions.




回答3:


Catching ArrayIndexOutofBoundsException wont help you andcatching runtime exceptions is a bad habbit . Fix the logic inside cellIsActive() method ..

Use http://www.tutorialspoint.com/java/java_exceptions.htm for more details



来源:https://stackoverflow.com/questions/21901875/java-dealing-with-exceptions-appropriately

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!