我有一个方法可以检查二维数组中的点,它还检查它们是否为空。我想抛出,ArrayIndexOutOfBoundsException
因为我已经检查了 null。
我在声明方法后尝试添加throws ArrayIndexOutOfBoundsException
,但它不起作用。我该怎么做呢?
我有一个方法可以检查二维数组中的点,它还检查它们是否为空。我想抛出,ArrayIndexOutOfBoundsException
因为我已经检查了 null。
我在声明方法后尝试添加throws ArrayIndexOutOfBoundsException
,但它不起作用。我该怎么做呢?
throws
在方法定义中说该方法可以抛出该异常。要实际将其放入方法主体中,请使用throw new ArrayIndexOutOfBoundsException();
试试这个:
throw new ArrayIndexOutOfBoundsException("this is my exception for the condition");
如果您只是将函数列为能够引发异常但从未在函数中实际引发异常,则不会生成异常。
如果您抛出异常但未将函数列为能够抛出异常,您可能会收到编译器错误或有关未捕获异常的警告。
您需要将您的函数列为抛出 ArrayIndexOutOfBoundsException 并在函数中的某处抛出异常。
例如:
public ... myArrayFunction(...) throws ArrayIndexOutOfBoundsException {
.... // handle the array
if (some condition) {
throw new ArrayIndexOutOfBoundsException("Array Index Out of Bounds");
}
}
基本上,throws
关键字告诉我们该方法可以抛出异常。如果要抛出任何类型的异常,则需要调用该类型的构造函数。
throw new NullPointerException("Null Pointer Exception");
在你的方法声明之后写:
private returnType methodName(CommunicationObject requestObject)
throws ArrayIndexOutOfBoundException {
}