Google+

223. Handling ArrayIndexOutOfBoundsException








Apart from AirthmeticException that we have handled in our previous posts, we have many other Run Time exceptions. To start with, I will explain 'ArrayIndexOutOfBoundsException' in this post.


ArrayIndexOutOfBoundsException - Each array consists of a concrete number of elements. For example int a[] = new int[2] contains two fixed number of elements i.e. a[0] & a[1]. But when you are trying to assign a value to a non existing element a[5] , or when you are trying to provide negative index value while assigning a value say a[-1], Java will throw ArrayIndexOutOfBoundsException.

Lets implement this on Eclipse IDE -

1. Launch Eclipse IDE, create a new Java Class file 'ArrayIndexOutOfBoundsExceptionDemo.java' with main( ) method in the existing project 'Project 46' as shown below -


2. Create an integer array with length 2 as shown below -



3. Now try to assign a value to a non-existing array element whose index is out of the given range as shown below -



4. Save and Run the 'ArrayIndexOutOfBoundsExceptionDemo.java' class file and observe that the program got terminated by printing the exception details in the Eclipse IDE -> Console as output -



5.  Now handle the occurred exception using 'ArrayIndexOutOfBoundsException' Class in try{ } catch{ } blocks as shown below -



6. Save and Run the  'ArrayIndexOutOfBoundsExceptionDemo.java' class file again and observe that the exception is handled using the ArrayIndexOutOfBoundsException Class in catch{ } block by giving the following output as shown below -




7. Now change the statement in the try from from a[5] to a[-1] to find out whether the exception is also occurring for the negative index of array as shown below -



8. Save and Run the  'ArrayIndexOutOfBoundsExceptionDemo.java' class file again and observe that the exception is handled using the ArrayIndexOutOfBoundsException Class in catch{ } block by giving the following output as shown below -


Since the statement in the above screen is printed in the output, the statement in the try{ } block i.e. array element having negative index value has thrown the 'ArrayIndexOutOfBoundsException' exception.

Hence we have used ArrayIndexOutOfBoundsException Class for handling the array index is out-of -bounds exception.






Please comment below to feedback or ask questions.

Using multiple catch blocks will be explained in the next post









No comments: