3

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

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

wattostudios
  • 8,666
  • 13
  • 43
  • 57
jocopa3
  • 796
  • 1
  • 10
  • 29

5 Answers5

9

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

tskuzzy
  • 35,812
  • 14
  • 73
  • 140
3

Try this:

throw new ArrayIndexOutOfBoundsException("this is my exception for the condition");
Code Maverick
  • 20,171
  • 12
  • 62
  • 114
shridatt
  • 896
  • 4
  • 15
  • 39
1

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.

For example:

public ... myArrayFunction(...) throws ArrayIndexOutOfBoundsException {
    .... // handle the array
    if (some condition) {
       throw new ArrayIndexOutOfBoundsException("Array Index Out of Bounds");
    }
}
MByD
  • 135,866
  • 28
  • 264
  • 277
user1258361
  • 1,133
  • 2
  • 16
  • 25
0

Basically the throws keyword 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.

throw new NullPointerException("Null Pointer Exception");
khael
  • 2,600
  • 1
  • 15
  • 36
Ahsan
  • 29
  • 1
0

After your method declaration write :

private returnType methodName(CommunicationObject requestObject)
            throws ArrayIndexOutOfBoundException {
}
RAS
  • 8,100
  • 16
  • 64
  • 86
PVR
  • 2,534
  • 18
  • 38