import java.util.*; // Random and Scanner public class Ch14_3 // program demonstrates use of ArrayIndexOutOfBoundsException by filling an array[100] with random elements { // and asking the user for an index to return the random value, but if the index is out of bounds, throw an exception public static void main(String[] args) { int[] values=new int[100]; // our array int i, index; // i used in the for loop, index is the input from the user which may be out of bounds Random g=new Random(); // used to randomly generate numbers Scanner s=new Scanner(System.in); // for input from user to get an index for(i=0;i<100;i++) values[i]=g.nextInt(10000)+1; // fill array with random values System.out.print("Enter an index, I will tell you the value (enter -9999 to quit): "); index=s.nextInt(); // get user's input index, could be out of bounds while(index!=-9999) // use a loop here so you can test out several values, notice the placement of the try and catch blocks inside this loop { try // try to access the array element { System.out.println("The value at index " + index + " is " + values[index]); // try to access values[index], may throw an Exception } catch(ArrayIndexOutOfBoundsException e) // on erroneous array element, get caught here { System.out.println(e); // output the exception } System.out.print("Enter an index, I will tell you the value (enter -9999 to quit: "); index=s.nextInt(); } // we could put more of the code inside the try block but really only the values[index] needs to go there } }