所以基本上我有一个 GridWorld 项目,我现在正在我的 AP Comp Sci 类(class)中进行。我在做吃 bean 人。这是我的 act 方法的代码(对于那些不熟悉 GridWorld 的人,每次预期 Actor 做出新 Action 时都会调用 act 方法):
public void act()
{
Location loc = getLocation();
if(direction==null) {
}
else if(direction.equals("NORTH")) {
Location next = loc.getAdjacentLocation(loc.NORTH);
if(getGrid().isValid(next) && (getGrid().get(next)==null || getGrid().get(next) instanceof Food)) {
if(getGrid().get(next) instanceof Food)
addFood();
moveTo(next);
direction = "NORTH";
}
}
else if(direction.equals("SOUTH")) {
Location next = loc.getAdjacentLocation(loc.SOUTH);
if(getGrid().isValid(next) && (getGrid().get(next)==null || getGrid().get(next) instanceof Food)) {
if(getGrid().get(next) instanceof Food)
addFood();
moveTo(getLocation().getAdjacentLocation(getLocation().SOUTH));
direction = "SOUTH";
}
}
else if(direction.equals("EAST")) {
Location next = loc.getAdjacentLocation(loc.EAST);
if(getGrid().isValid(next) && (getGrid().get(next)==null || getGrid().get(next) instanceof Food)) {
if(getGrid().get(next) instanceof Food)
addFood();
moveTo(getLocation().getAdjacentLocation(getLocation().EAST));
direction = "EAST";
}
else if(getLocation().getCol()==20 && getLocation().getRow()==9) {
moveTo(new Location(9,0));
direction = "EAST";
}
}
else if(direction.equals("WEST")) {
Location next = loc.getAdjacentLocation(loc.WEST);
if(getGrid().isValid(next) && (getGrid().get(next)==null || getGrid().get(next) instanceof Food)) {
moveTo(getLocation().getAdjacentLocation(getLocation().WEST));
direction = "WEST";
}
else if(getLocation().getCol()==0 && getLocation().getRow()==9) {
moveTo(new Location(9,20));
direction = "WEST";
}
}
}
最后两个 if 语句中措辞奇怪的原因是因为我希望吃 bean 人能够在真实游戏中传送。现在,当我运行游戏时,大约 90% 的时间它工作,但在另外 10% 的时间我得到一个 IllegalArgumentException bc 它说我正在尝试移动到一个不在棋盘上的地方(例如。(9,-1 ) 和 (9,21))。我想知道如何 catch 或投球,或者我需要做些什么来阻止这种情况发生。我从未使用过 catch 或 throw 所以也请尝试解释你的推理谢谢!
最佳答案
要抛出异常,您可以使用关键字throw
。要捕获,您可以使用 try/catch 结构。有关更多详细信息,请参见:
对于你的情况,你会做这样的事情 - 这是一个测试用例:
try {
throw new IllegalArgumentException("Threw an IllegalArgumentException");
} catch(IllegalArgumentException e) {
System.out.println("Caught an IllegalArgumentException..." + e.getMessage());
}
但是,您应该查看您的代码以了解为什么会抛出 IllegalArgumentException 并修复该部分。使用异常和 try/catch 是针对意外 事件,而不是您期望发生并且您可以以更好的方式处理的事件。
例如,FileNotFoundException找不到文件时抛出。您通常会尝试/捕获它,以便在找不到文件时执行某些操作。但是,如果预计在合理数量的情况下该文件可能不存在,则最好先检查该文件是否存在,然后检查它是否确实对它执行了某些操作。
关于java - 如何抛出并捕获 IllegalArgumentException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9369057/