3

我有一个方法可以检查二维数组中的点,它还检查它们是否为空。我想抛出,ArrayIndexOutOfBoundsException因为我已经检查了 null。

我在声明方法后尝试添加throws ArrayIndexOutOfBoundsException,但它不起作用。我该怎么做呢?

4

5 回答 5

9

throws在方法定义中说该方法可以抛出该异常。要实际将其放入方法主体中,请使用throw new ArrayIndexOutOfBoundsException();

于 2012-03-29T04:18:31.297 回答
3

试试这个:

throw new ArrayIndexOutOfBoundsException("this is my exception for the condition");
于 2012-03-29T04:22:55.967 回答
1

如果您只是将函数列为能够引发异常但从未在函数中实际引发异常,则不会生成异常。

如果您抛出异常但未将函数列为能够抛出异常,您可能会收到编译器错误或有关未捕获异常的警告。

您需要将您的函数列为抛出 ArrayIndexOutOfBoundsException 并在函数中的某处抛出异常。

例如:

public ... myArrayFunction(...) throws ArrayIndexOutOfBoundsException {
    .... // handle the array
    if (some condition) {
       throw new ArrayIndexOutOfBoundsException("Array Index Out of Bounds");
    }
}
于 2012-03-29T16:04:48.803 回答
0

基本上,throws关键字告诉我们该方法可以抛出异常。如果要抛出任何类型的异常,则需要调用该类型的构造函数。

throw new NullPointerException("Null Pointer Exception");
于 2012-03-29T04:30:02.237 回答
0

在你的方法声明之后写:

private returnType methodName(CommunicationObject requestObject)
            throws ArrayIndexOutOfBoundException {
}
于 2012-03-29T04:33:26.473 回答