How to handle ArrayIndexOutOfBoundsException :JAVA ,ANDROID
java.lang.ArrayIndexOutOfBoundsException
java.lang.ArrayIndexOutOfBoundsException occurs when we try to access an element of an array, with an index that is negative or more than the size of array itself. Usually, one would come across “java.lang.ArrayIndexOutOfBoundsException: 4” which occurs when an attempt is made to access (4+1)fifth element of an array, despite the size of array being less than five.
Lets see a sample program that could produce this exception:
public class ArrayIndexOutOfBoundsExceptionExceptionExample {
public static void main(String[] args) {
String[] names = new String[3];
names[0] = "Sherlock";
names[1] = "Watson";
names[2] = "Mary";
System.out.println(names[4]);
}
}
|
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at com.tutorialkart.java.ArrayIndexOutOfBoundsExceptionExceptionExample.main(ArrayIndexOutOfBoundsExceptionExceptionExample.java:12)
|
Let us see “java.lang.ArrayIndexOutOfBoundsException: 4” in detail:
- java.lang.ArrayIndexOutOfBoundsException : Exception thrown by java language while trying to access an element of array with an index that is out of the range of
- 4 : is the index of element, that we tried to access in the array. This goes in, while creating the exception object.
How to handle ArrayIndexOutOfBoundsException ?
Let’s handle the ArrayIndexOutOfBoundsException using try-catch.
- Surround the statements that could throw ArrayIndexOutOfBoundsException with try-catch block.
- Catch ArrayIndexOutOfBoundsException.
- Take necessary action for the further course of your program, as you are handling the exception and the execution doesn’t abort.
public class ArrayIndexOutOfBoundsExceptionExceptionExample {
public static void main(String[] args) {
String[] names = new String[3];
names[0] = "Sherlock";
names[1] = "Watson";
names[2] = "Mary";
System.out.println(names[1]);
try {
System.out.println(names[4]);
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
System.out.println("The index used is out of the bounds of array.\n"
+ "Deal with it.");
}
System.out.println("The execution of further statements continues.");
}
}
|
Watson
java.lang.ArrayIndexOutOfBoundsException: 4
at com.tutorialkart.java.ArrayIndexOutOfBoundsExceptionExceptionExample.main(ArrayIndexOutOfBoundsExceptionExceptionExample.java:14)
The index used is out of the bounds of array.
Deal with it.
The execution of further statements continues.
|
Post a Comment
0Comments