Reputation: 89
So I have a program that I want to check if a set of cords are inside a gameboard, and if they are not, to throw an error, but continue with the program. Here is the code used (I'm not worried about class/package names):
package routines;
import java.util.Random;
import game.GameBoard;
import game.Player;
public class MovePlayer extends Routine {
final protected int destX;
final protected int destY;
public MovePlayer(int destX, int destY, GameBoard board) {
super();
if(destY > board.getHeight() || destX > board.getWidth()) {
fail();
throw new RuntimeException(">>> Error while creating routine, one or more coords are outside of the game board");
} else {
this.destX = destX;
this.destY = destY;
}
}
And here is a link to the super class (a lot of code, not sure if I should put all of it in here) Super class SRC
EDIT: Not sure if this will fix what I was wanting, but all I did was remove the final
keyword from the variables
EDIT #2: So I finally figured what I was doing wrong. 1) the variables were marked as final. 2) It was some of my other code that was causing this to happen *facepalm* All of my code has been pushed to a new Git repository, so if you should so choose, you can look at what I did here: VI-Arena Git repository
Upvotes: 1
Views: 19224
Reputation: 89
I figured out what and how to do what I was needing. What I needed to stop the creation of the routine object if conditions were met, and that was done by throwing an error. That was being done, but I was mistakenly setting the variables INSIDE the try...catch
block. So, if the conditions are not satisfied, it fails and stops, if they are satisfied, it creates the object and sets the variables OUTSIDE of the try...catch
block, which works. My new code is as follows:
package routines;
import java.io.IOException;
import java.util.Random;
import game.*;
public class MovePlayer extends Routine {
private final int destX;
private final int destY;
private final Random random = new Random();
public MovePlayer(int destX, int destY, GameBoard board) throws IOException {
super();
try {
if (destY > board.getHeight() || destX > board.getWidth()) {
throw new IllegalArgumentException(">>> Error while creating routine, one or more coords are outside of the game board");
} else {
}
} catch (IllegalArgumentException e) {
fail();
System.err.println(e.getLocalizedMessage());
}
this.destX = destX;
this.destY = destY;
}
Upvotes: 3
Reputation: 5322
By using the
try{
}
catch(Exception){
}
finally{
}
block you can handle exceptions instead of letting them crash your program!
Your code comes in the try block, and in the catch block you can handle the Exception which is being thrown from the executing code in the try-block.
The finally block is used to close or finalize used resources in order to not leave them opened. Not doing that might - ironically - throw you even more exceptions.
I would definitely look up on that, it's a very commonly used part of modern languages!
Upvotes: 1