Java 尝试捕获 ArrayIndexOutOfBoundsException?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25936890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
try catch ArrayIndexOutOfBoundsException?
提问by Denniz
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.
我的项目由一个在尺寸为 25 x 20 的网格上移动的小图标组成。我知道我可以使用一些 if/else 块轻松完成此操作,但我想了解有关错误处理的更多信息。
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.
我在想的是使用 try catch,但它不会捕获数组索引越界异常或任何异常Exception
:它不会返回“错误”或位置,因此它永远不会进入 catch 块。
I was thinking something like this pseudocode:
我在想这样的伪代码:
try {
// Code
} catch(The exception) {
x - 1 or + 1
}
Actual code:
实际代码:
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";
}
采纳答案by Ideasthete
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 块没有捕获任何内容的原因(我假设被调用的方法之一中有一个数组?)。此外,您真的,真的不应该让您的程序读取数组范围之外的内容。那只是糟糕的设计。话虽如此,以下是您如何以我能想到的最清晰的方式捕获异常:
try {
array[index] = someValue;
}
catch(ArrayIndexOutOfBoundsException exception) {
handleTheExceptionSomehow(exception);
}
Or do as @Peerhenry suggests and just throw a new Exception if the indices aren't correct, which would be a much better design.
或者按照@Peerhenry 的建议进行操作,如果索引不正确,则抛出一个新的异常,这将是一个更好的设计。
回答by Peerhenry
Putting code within a try catch block only makes sense if one or more methods inside can throw exceptions. You can throw an exception like this:
仅当其中的一个或多个方法可以抛出异常时,将代码放入 try catch 块中才有意义。你可以抛出这样的异常:
public static void setPosition(int x, int y) throws Exception
{
if(x<0 || y<0) throw new Exception("coordinate components must be greater than zero");
else...
}
回答by Abhishec Kumar
try {
//code related something to array
}
catch(ArrayIndexOutOfBoundsException ignored) {
}