我对这个 try/catch 语句感到困惑
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;
}
}
这应该如何工作:horizontal[]和vertical[]是两个int[],每个int[]保存国际象棋骑士可能的移动的值,即2个水平和1个垂直输出将是一个移动。然后它应该为“方 block ”分配一个非零的移动数。 try/catch 位应该捕获棋盘外的任何移动,增加 x,然后再次执行循环。但每当它执行该语句时,它都不会再次执行第一个 if ;相反,它会转到第二个 if 并生成异常。我不确定什么语句会以这种方式返回控制权。
最佳答案
你写道:
The try/catch bit should catch any moves out of the board, increment x, and then go through the loop again.
不,不应该。您似乎正在考虑异常处理程序(“捕获位”),就好像它是异常发生时调用的方法,它将控制权返回到调用它的位置。他们不是这样工作的。
当代码中发生ArrayIndexOutOfBoundsException
时,控制会跳转到异常处理程序。 try
block 中代码的所有处理都会终止——不会恢复。执行catch
block 中的代码。如果x==8
你的方法将返回一个值;但除此之外,您的异常处理程序只会增加 x 并结束。这意味着代码的执行将在 catch
block 结束后开始执行。您还没有显示方法的其余部分 - 我认为必须有更多方法,因为它需要返回一个值 - 所以我不能确定接下来会发生什么,但这可能会导致许多问题。
异常处理在这里根本不合适。明确地根据棋盘的大小测试您的坐标。
关于java - Try/Catch 和循环控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5491298/