开发者

Try/Catch and Loop Control

I'm confused about this try/catch statement

public int MakeMove() {
    int x = 0; //counter for moves

    try {
        // tests to see if potential move has been reached
        if (board[currentRow + (vertical[x])][currentColumn + (horizontal[x])] != 0) {
            // increments x until a good move is reached.
            while ((board[currentRow + (vertical[x])][currentColumn + (horizontal[x])] != 0)) {
                x++;
                if (x == 8) { //breaks if all moves are tried
                    return 1;
                }
            } 
        }
    }
    //should catch any tries to move piece off board, catches the exception and increments x
    catch(ArrayIndexOutOfBoundsException e) {
        x++;
        if(x == 8) {//breaks if all moves are tried
            return 1;
        }
    }

How this should work: horizontal[] and vertical[] are two int[]s which each hold the value for a chess knight's possible moves, i.e. 2 horizontal and 开发者_如何学运维1 vertical out would be one move. Then it should assign a non zero movenumber to the "square". The try/catch bit should catch any moves out of the board, increment x, and then go through the loop again. But whenever it goes through the statement it doesn't go through the first if again; instead it goes to the second if and generates an exception. I'm not sure what statement would return control in that way.


You wrote:

The try/catch bit should catch any moves out of the board, increment x, and then go through the loop again.

No, it shouldn't. You seem to be thinking of an exception handler (the "catch bit") as if it is a method that is called when an exception happens, that will return control back to where it was called from. That's not how they work.

When an ArrayIndexOutOfBoundsException occurs in your code, control jumps to the exception handler. All processing of the code within the try block is terminated -- it's not going to be resumed. The code within the catch block is executed. If x==8 your method will return a value; but otherwise, your exception handler just increments x and ends. That means that execution of your code picks up after the end of the catch block. You haven't shown the rest of your method -- I think there must be more since it is required to return a value -- so I can't say for sure what's happening next, but this could lead to any number of problems.

Exception handling is simply inappropriate here. Test your coordinates against the size of the board explicitly.


Move the try catch inside the loop if you want it to reenter the loop after the catch body finishes.

But really, listen to everybody who says you shouldn't use exceptions for this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜