import java.util.*;
public class ArrayIndexOutOfBoundsException {
public static void main(String[] args) {
int[] array = new int[100];
//creating array with 100 storage spaces for(int i = 0; i < array.length; i++) { //for loop to store random integers in each index of the array array[i] = (int) (Math.random()*100); }
Scanner input = new Scanner(System.in);
System.out.println("Enter the index of the array: ");
//prompting user to enter index to find
try {
int index = input.nextInt(); //declaring index variable to take on inputed value
System.out.println("The integer at index "+index+" is: "+array[index]); //printing the integer at the specified index
}
catch (ArrayIndexOutOfBoundsException ex) { //if user enters index value outside of 0-99, exception message will print
System.out.println("Out of bounds.");
}
}
}
When your code is being compiled to the byte code, the compiler has to discover all classes and extend all names into their FQDNs - packages + class name
In your case, when the programs is compiled, the main class name is ArrayIndexOutOfBoundsException - so the compiler maps ArrayIndexOutOfBoundsException to your own class.
When compiler gets to catch line, it takes ArrayIndexOutOfBoundsException and tries to first locate it in the map - and it is there. So the compilers starts checking the correctness, in particular, the class has to be in Throwable hierarchy. Since it is not in throwable hierarchy (your class implicitly extends Object), the compiler returns an error.
You could fix it using two ways:
The second options helps with a generic problem: what if two classes have the same name, but have to be used in the same scope.