尝试捕获ArrayIndexOutOfBoundsException?

Den*_*niz 1 java error-handling

我的项目包含一个小图标,在网格上移动,尺寸为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)

Ide*_*ete 15

我没有在你的代码中的任何地方看到一个数组,所以这可能是为什么try块没有捕获任何东西(我假设在一个被调用的方法中有一个数组?).而且,你真的,真的不应该允许你的程序在数组的边界之外读取.那只是糟糕的设计.话虽如此,这里是你如何以我能想到的最清晰的方式捕捉异常:

try {
    array[index] = someValue;
}
catch(ArrayIndexOutOfBoundsException exception) {
    handleTheExceptionSomehow(exception);
}
Run Code Online (Sandbox Code Playgroud)

或者像@Peerhenry建议的那样做,如果索引不正确则抛出一个新的Exception,这将是一个更好的设计.