java 如何抛出 ArrayIndexOutOfBoundsException?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9918992/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:54:15  来源:igfitidea点击:

How to throw ArrayIndexOutOfBoundsException?

javaarraysthrowindexoutofboundsexception

提问by jocopa3

I have a method that checks spots in a 2D array, and it also checks if they are null. I want to throw the ArrayIndexOutOfBoundsExceptionbecause I already check for null.

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

I tried adding throws ArrayIndexOutOfBoundsExceptionafter declaring the method, but it doesn't work. How do I do this?

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

回答by tskuzzy

throwsin the method definition says that the method can throw that exception. To actually throw it in the method body, use throw new ArrayIndexOutOfBoundsException();

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

回答by shridatt

Try this:

试试这个:

throw new ArrayIndexOutOfBoundsException("this is my exception for the condition");

回答by user1258361

If you just list the function as being able to throw an exception but never actually throw the exception in the function, no exception is ever generated.

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

If you throw the exception but don't list the function as being able to throw an exception, you may get a compiler error or warning about an uncaught exception.

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

You need to list your function as throwing an ArrayIndexOutOfBoundsException and throw the exception somewhere in your function.

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

For example:

例如:

public ... myArrayFunction(...) throws ArrayIndexOutOfBoundsException {
    .... // handle the array
    if (some condition) {
       throw new ArrayIndexOutOfBoundsException("Array Index Out of Bounds");
    }
}

回答by Ahsan

Basically the throwskeyword tells us that the method can throw the exception .If you want to throw any kind of exception you need to call the constructor of that type.

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

throw new NullPointerException("Null Pointer Exception");

回答by PVR

After your method declaration write :

在你的方法声明之后写:

private returnType methodName(CommunicationObject requestObject)
            throws ArrayIndexOutOfBoundException {
}