This method checks to see if the proposed move can be made.
My lab says "You are not expected to catch the exception, just be sure it is thrown in the appropriate place. "
But for my final assignment we have to turn it into a try catch statement. My issue with the code is that there is 2 separate if else statements.
This code
// no errors, proceed with move GamePiece locationFrom = board[fromX][fromY]; GamePiece locationTo = board[toX][toY];
Can't be moved on top because you get a runtime error when you set fromX to -445 or something because that position doesn't exist. When really it should be doing my throw statement.
/** * move gamepiece method */ public void movePiece(Location from, Location to) throws InvalidMoveException { int fromX = from.getXPosition(); int fromY = from.getYPosition(); int toX = to.getXPosition(); int toY = to.getYPosition(); if((fromX < 0 || fromX >= ROW) || (fromY < 0 || fromY >= ROW)){ throw new InvalidMoveException("Location FROM position is out of bounds"); } else if((toX < 0 || toX >= COLUMN) || (toY < 0 || toY >= COLUMN)){ throw new InvalidMoveException("Location TO position is out of bounds"); } // no errors, proceed with move GamePiece locationFrom = board[fromX][fromY]; GamePiece locationTo = board[toX][toY]; if(board[fromX][fromY] == null){ throw new InvalidMoveException("You cant move a piece that isn't there"); } else if(!locationFrom.isLegalMove(from, to)){ throw new InvalidMoveException("Not a valid move: You can only move pieces up"); } board[toX][toY] = locationFrom; board[fromX][fromY] = null; }