Array IndexOutofbounds Exception in Java: When we require to store values, then we should go with variables. But when we require to store some same data type element then that time we should go with Array.
Issues In Array:
There are so many benefits of using Array in our program, but also there is some drawback or issues are appearing when you are dealing with that array and the array elements.
We are facing below issues when we are dealing with an array:
- Arrays are fixed in size so if we don’t know the required size then its a problem
- If we Assign more size as compare to requirement, then we waste the memory
- if we assign min size to an array, then it will create the problem.
Check Also: Exception Handling Interview Questions & Answers
Exceptions Come in Array:
When you perform some operation in an array, they may be some time you can face some exception. Here is some exception related to array
- Array IndexOutofbounds Exception
When Can You Get Array IndexOutofbounds Exception?
- Suppose an Array has size 10, but you want to access the 11th element of an array, in that case, you will get ArrayIndex Exception.
- Similarly, if you try to access an array element by giving a negative value that time also you can get ArrayIndex Exception.
How to Handel Array IndexOutofbounds Exception
We Can Handel ArrayIndex Exception in two ways:
- Using the for-each loop
- Using Try-catch
Using the for-each loop:
Without mentioning the size of an array, we can access the elements of a display by using for each loop, for example
for(int element : array) { }
Using Try-catch:
As we know to handle or overcome from the exception there is a concept is there, that’s called TRY CATCH. We can put those statement under try block which may generate an exception. And in the catch block, we write those statement to handle an exception.
package co.java.exception; public class ArrayIndexException { public static void main(String[] args) { int[] arr=new int[3]; arr[0]=10; arr[1]=20; arr[2]=30; arr[3]=40; // Here You Get The exception for(int i=0;i<arr.length;i++) { System.out.println(arr[i]); } } }
Leave a Reply