所以我有一个程序,我想检查一组绳索是否在游戏板内,如果不在,则抛出错误,但继续执行该程序。这是使用的代码(我不担心类/包名称):
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;
}
}
这里是父类(super class)的链接(很多代码,不确定我是否应该把所有的都放在这里)Super class SRC
编辑:不确定这是否会解决我想要的问题,但我所做的只是从变量中删除 final
关键字
编辑#2:所以我终于明白我做错了什么。 1)变量被标记为最终的。 2) 是我的一些其他代码导致了这种情况发生*facepalm* 我所有的代码都被推送到一个新的 Git 存储库中,所以如果你应该选择,你可以看看是什么我在这里做的:VI-Arena Git repository
最佳答案
我想出了我需要做什么以及如何做。如果满足条件,我需要停止创建例程对象,这是通过抛出错误来完成的。已经完成了,但我错误地在 try...catch
block 中设置了变量。因此,如果条件不满足,它就会失败并停止,如果条件满足,它会创建对象并在 try...catch
block 的外部设置变量,这是有效的。我的新代码如下:
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;
}
关于java - 在 Java 中抛出异常而不终止程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32081044/