java怎么抛出警告信息_java – 如何抛出并捕获IllegalArgumentException?

所以基本上我有一个GridWorld项目,我现在正在AP Comp Sci课上做.我在做Pacman.这是我的act方法的代码(对于那些不熟悉GridWorld的人来说,每当一个actor被要求做出新动作时都会调用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语句中出现奇怪措辞的原因是bc我希望Pacman能够在真实游戏中传送.现在,当我运行游戏时,大约90%的时间它可以工作但是在另外10%中我得到一个IllegalArgumentException bc它说我试图移动到一个不在板上的地方(例如.(9,-1) )和(9,21)).我想知道如何抓住或抛出或我需要做些什么来阻止这种情况发生.我从来没有使用过捕获或抛出,所以请尝试解释你的推理谢谢!

解决方法:

要抛出异常,请使用关键字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,gridworld

来源: https://codeday.me/bug/20190621/1251006.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值