我的项目包含一个小图标,在网格上移动,尺寸为25×20.我知道我可以使用一些if/else块轻松完成这项工作,但我想了解更多有关错误处理的信息.
我在想的是使用try catch,但是它没有捕获数组索引超出边界的异常或者Exception根本没有:它没有返回"错误"或位置,所以它永远不会进入catch块.
我在想像这样的伪代码:
try {
// Code
} catch(The exception) {
x - 1 or + 1
}
Run Code Online (Sandbox Code Playgroud)
实际代码:
public void tick() {
Random rand = new Random();
try {
int x, y;
x = rand.nextInt(3) + (-1); //Slumpar fram en siffra (-1, 0, 1)
y = rand.nextInt(3) + (-1);
setPosition(new Point((int)getPosition().getX()+x,(int)getPosition().getY() + y));
} catch(Exception e) {
System.out.println("error");
}
System.out.println("x: " + getPosition().getX());
System.out.println("y: " + getPosition().getY());
}
public String type() {
return "Dummy";
}
Run Code Online (Sandbox Code Playgroud)