Java for Android Tutorial#9: ArrayOutofBoundException




In this program, I have shown how to handle array-out-of-bound-exception with little effort. As my focus was simplicity, I have simply use the console printing for handling the exception.

Code:

package com.example;

public class java {

    public static void main(String[] str) {

        String[] names = {"James","Ashley","Kevin","June"};

        for (int i = 0; i < names.length + 1; i = i + 1){

            try {

                System.out.println(names[i]);

            }

            catch(ArrayIndexOutOfBoundsException e){

                System.out.println("You are trying to access index" + i + ",while the maximum index of the Array is "+(names.length - 1));

            }

        }

    }



}


Comments