我很困惑这个try/catch语句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;
}
}
应如何工作的:水平[]和垂直[]是两个int []里每个持有价值国际象棋骑士可能的举动,即2水平和1垂直是一举。然后它应该给“广场”分配一个非零的莫文字。 try/catch位应该抓住任何移出的棋盘,增加x,然后再次通过循环。但是,只要它通过声明,它不会再经历第一次;相反,它会转到第二个if并产生一个异常。我不确定哪种说法会以这种方式返回控制权。
只是为了将来的设计,您不应该将异常用作正常程序逻辑的一部分。 – 2011-03-30 19:35:32
+1 Chris。 @Alex,你想以这样一种方式来构建你的代码,即不会发生异常。他们是EXCEPT,而不是期望。 :-) – corsiKa 2011-03-30 19:37:48
永远不要使用try-catch异常处理作为流程控制结构。仅用于异常处理。恕我直言,这是糟糕的Java代码。 – PeterMmm 2011-03-30 19:38:54