【问题标题】:How to throw ArrayIndexOutOfBoundsException?如何抛出 ArrayIndexOutOfBoundsException?
【发布时间】:2012-04-12 17:21:07
【问题描述】:
我有一个方法可以检查二维数组中的点,它还会检查它们是否为空。我想抛出ArrayIndexOutOfBoundsException,因为我已经检查了空值。
我尝试在声明方法后添加throws ArrayIndexOutOfBoundsException,但它不起作用。我该怎么做呢?
【问题讨论】:
标签:
java
arrays
throw
indexoutofboundsexception
【解决方案1】:
throws 在方法定义中表示该方法可以抛出该异常。要实际将其放入方法体中,请使用throw new ArrayIndexOutOfBoundsException();
【解决方案2】:
试试这个:
throw new ArrayIndexOutOfBoundsException("this is my exception for the condition");
【解决方案3】:
基本上throws 关键字告诉我们该方法可以抛出异常。如果要抛出任何类型的异常,您需要调用该类型的构造函数。
throw new NullPointerException("Null Pointer Exception");
【解决方案4】:
在你的方法声明之后写:
private returnType methodName(CommunicationObject requestObject)
throws ArrayIndexOutOfBoundException {
}
【解决方案5】:
如果您只是将函数列为能够引发异常但从未在函数中实际引发异常,则永远不会生成异常。
如果您抛出异常但未将函数列为能够抛出异常,您可能会收到编译器错误或有关未捕获异常的警告。
您需要将您的函数列为抛出 ArrayIndexOutOfBoundsException 并在函数的某处抛出异常。
例如:
public ... myArrayFunction(...) throws ArrayIndexOutOfBoundsException {
.... // handle the array
if (some condition) {
throw new ArrayIndexOutOfBoundsException("Array Index Out of Bounds");
}
}