
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Handle Java Array Index Out of Bounds Exception
Generally, an array is of fixed size and each element is accessed using the indices. For example, we have created an array with size 9. Then the valid expressions to access the elements of this array will be a[0] to a[8] (length-1).
Whenever you used an –ve value or, the value greater than or equal to the size of the array, then the ArrayIndexOutOfBoundsException is thrown.
For Example, if you execute the following code, it displays the elements in the array asks you to give the index to select an element. Since the size of the array is 7, the valid index will be 0 to 6.
Example
import java.util.Arrays; import java.util.Scanner; public class AIOBSample { public static void main(String args[]) { int[] myArray = {897, 56, 78, 90, 12, 123, 75}; System.out.println("Elements in the array are:: "); System.out.println(Arrays.toString(myArray)); Scanner sc = new Scanner(System.in); System.out.println("Enter the index of the required element ::"); int element = sc.nextInt(); System.out.println("Element in the given index is :: "+myArray[element]); } }
But if you observe the below output we have requested the element with the index 9 since it is an invalid index an ArrayIndexOutOfBoundsException raised and the execution terminated.
Output
Elements in the array are:: [897, 56, 78, 90, 12, 123, 75] Enter the index of the required element :: 7 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7 at AIOBSample.main(AIOBSample.java:12)
Handling the exception
You can handle this exception using try catch as shown below.
Example
import java.util.Arrays; import java.util.Scanner; public class AIOBSampleHandled { public static void main(String args[]) { int[] myArray = {897, 56, 78, 90, 12, 123, 75}; System.out.println("Elements in the array are:: "); System.out.println(Arrays.toString(myArray)); Scanner sc = new Scanner(System.in); System.out.println("Enter the index of the required element ::"); try { int element = sc.nextInt(); System.out.println("Element in the given index is :: "+myArray[element]); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("The index you have entered is invalid"); System.out.println("Please enter an index number between 0 and 6"); } } }
Output
Elements in the array are:: [897, 56, 78, 90, 12, 123, 75] Enter the index of the required element :: 7 The index you have entered is invalid Please enter an index number between 0 and 6