Home > OS >  I am receiving an error: no exception of type ArrayIndexOutOfBoundsException can be thrown; an excep
I am receiving an error: no exception of type ArrayIndexOutOfBoundsException can be thrown; an excep

Time:03-04

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.");
        }

        
    } 
        
}

CodePudding user response:

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:

  1. rename you main class to avoid ambiguity
  2. in catch you may specify full name for the class: java.lang.ArrayIndexOutOfBoundsException

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.

CodePudding user response:

The ArrayIndexOutOfBoundsException exception type is included in the java/lang package. So you have to import it or use the full name in your catch clause:

catch (java.lang.ArrayIndexOutOfBoundsException ex)

In your situation, import won't work because your class is also called ArrayIndexOutOfBoundsException so you'll need to use the full name in the catch clause.

As a final advice, I recommend you rename your class as a good practice cause as it is now, it could lead to confusion and turn the code difficult to read.

  • Related