有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java适当地处理异常

不太熟悉JAVA或异常处理。寻找一些关于什么是可以接受的,什么是不赞成的建议

在这个场景中,我正在构建一个生命游戏程序,我设置了一些条件来检查一个单元格是否会越界,而不是试图访问那个“单元格”。我的问题是,使用try-catch块而不是8个条件是否可以接受,如果抛出arrayOutOfBounds异常,则什么也不做。ie忽略超出范围的单元格,还是这种做法不好?例如

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

在此场景中,cellIsAlive方法检查多维数组中的位置,如果该位置处于活动状态,则返回1,否则返回0,并抛出ArrayIndexOutofBoundsException

这样使用异常是个好主意还是不好的做法

提前感谢您的任何意见


共 (3) 个答案

  1. # 2 楼答案

    这绝对是一种糟糕的做法。异常处理会消耗大量资源,并且应该仅在异常情况下使用(顾名思义)

    看看这本书的第9章(如果可以的话,还可以阅读其他章节):

    http://www.amazon.com/Effective-Java-Edition-Joshua-Bloch/dp/0321356683/

    你会发现,你试图做的事情与用来说明你不应该做的事情的例子非常相似,我引用:

    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. # 3 楼答案

    RuntimeExcepions是一种不好的习惯ArrayIndexOutofBoundsExceptionRuntimeException的一个子类RuntimeExceptions如果程序员有错误,您应该只捕获检查过的异常