尝试捕获ArrayIndexOutOfBoundsException吗? [英] try catch ArrayIndexOutOfBoundsException?

查看:362
本文介绍了尝试捕获ArrayIndexOutOfBoundsException吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目包括一个在尺寸为25 x 20的网格上移动的小图标。我知道我可以使用几个if / else块轻松地做到这一点,但是我想了解有关错误处理的更多信息。

My project consists of a little icon moving over a grid with dimensions 25 by 20. I know I can do this easily with a few if/else blocks, but I want to learn more about error handling.

我在想的是使用try catch,但是它没有捕获数组索引超出范围异常或任何 Exception :它不会返回错误或位置,所以它永远不会到达catch块。

What I was thinking was using a try catch, but it doesn't catch the array index out of bounds exception or any Exception at all: it does not return "error" or the positions, so it never goes to the catch block.

我在想这样的伪代码:

I was thinking something like this pseudocode:

try {
    // Code
} catch(The exception) {
   x - 1 or + 1
}

实际代码:

 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";
}


推荐答案

我看不到数组在代码中的任何位置,所以这就是为什么try块没有捕获任何东西的原因(我假设其中一个被调用的方法中有一个数组?)。另外,您确实不应该允许您的程序在数组范围之外进行读取。那只是不好的设计。话虽这么说,这是您以我能想到的最清晰的方式捕获异常的方法:

I don't see an array anywhere in your code, so that's maybe why the try block isn't catching anything (I assume there is an array in one of the called methods?). Also, you really, really shouldn't allow your program to read outside the bounds of an array. That's just bad design. That being said, here is how you would catch the exception in the clearest way I can think of:

try {
    array[index] = someValue;
}
catch(ArrayIndexOutOfBoundsException exception) {
    handleTheExceptionSomehow(exception);
}

或者按照@Peerhenry的建议进行操作,如果索引不是是不正确的,这将是一个更好的设计。

Or do as @Peerhenry suggests and just throw a new Exception if the indices aren't correct, which would be a much better design.

这篇关于尝试捕获ArrayIndexOutOfBoundsException吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆