不知道为什么我在尝试调用我的方法时遇到异常

时间:2012-01-22 20:47:16

标签: java exception

好的,所以我应该使用例外来放置战舰,以确保没有规则被破坏。然而,当我尝试调用该函数时,我得到了这个:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    Unhandled exception type Exception
    at BattleshipBoard.main(BattleshipBoard.java:135)

不是100%肯定我做错了什么,如果你们能够找出错误的原因,那么我明显打破它的相关规则将受到高度赞赏。

这是相关代码:

public void placeShip(int startCol, int startRow, int endCol, int endRow)
        throws Exception {
            if(startCol > numCols) {
                throw new Exception("0");
            }
            if(startCol < 0 ) {
                throw new Exception("Out of bounds, less than 1(startCol)");
            }
            if (startRow > numRows) {
                throw new Exception("Out of bounds, Greater then numRows");
            }
            if (startRow < 0) {
                throw new Exception("Out of bounds, less than 1 (startRow)");
            }
            if((startCol != endCol) && (startRow != endRow)){
                throw new Exception("Diag");
            }
            if(board[i][j] == 1){
                throw new Exception("Overlap");
            }
            if (startCol == endCol){
                for (i = startCol; i <= endCol; i++ ){
                    board[i][j] = 1;
                }
            }
            if (startRow == endRow){
                for(j = startRow; j <= endRow; j++){
                    board[i][j] = 1;
                }
            }


}

public static void main(String args[]) {
    // You may leave this empty
    BattleshipBoard b = new BattleshipBoard(10, 10);
    b.placeShip(0, 0, 3, 0);
}

4 个答案:

答案 0 :(得分:1)

您没有处理placeShip可以抛出的异常。您应该将placeShip调用放在try块

try{
b.placeShip(0, 0, 3, 0);
}
catch(Exception x){
// take some action
}

这样,如果placeShip抛出异常,你的程序就不会崩溃。

答案 1 :(得分:1)

Java检查了异常。做到这一点:

try {
 b.placeShip(0, 0, 3, 0);
} catch(Exception e) {
System.err.println("error: "+e.getMessage());
}

但是,使用Exception不是一个好主意。更好地创建自己的例外Exception这样就可以相应地处理不同的规则违规行为。

答案 2 :(得分:1)

Checked exceptions should either be catched or re-thrown.所以,你有两个选择

  1. 声明main(..)方法抛出异常或
  2. sorround b.placeShip(...)with try-catch

答案 3 :(得分:1)

为什么需要这些for循环?

        if (startCol == endCol){
            for (i = startCol; i <= endCol; i++ ){
                board[i][j] = 1;
            }
        }
        if (startRow == endRow){
            for(j = startRow; j <= endRow; j++){
                board[i][j] = 1;
            }
        }

如果初始值等于最终值,则循环只会执行一次。只是做:

board[startCol][j] = 1;
board[i][startRow] = 1;

我还怀疑你在这部分代码中得到了“索引数组越界异常”。