javaarraysobjectbinary-searchlinear-search

Try catch for ArrayIndexOutOfBoundsException


I am running a test for Binary search method for a value which is not found in an object array by using the try catch block, but the error ArrayIndexOutOfBoundsException is still being thrown.

Please refer to below code

int high = foodlist.length - 1;
int result = foodObj.binarySearch(foodlist, 0, high , key);

    try {
        if (result != -1)
            System.out.println("Element is found at index: " + result);
        else
            throw new ArrayIndexOutOfBoundsException();
    } 
    catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("Element not found!");
        System.out.println("Please enter an ID in the range of 1 to 3");
    }

    // Binary Search method
public static int binarySearch(Food[] foodlist, int low, int high, int value) {
    
    if (high >= low) {
        int mid = low + (high - low) / 2;
        
        if (foodlist[mid].id == value)
            return mid;
        
        else if (foodlist[mid].id > value)
            return binarySearch(foodlist, low, mid-1, value);
        else 
            return binarySearch(foodlist, high, mid+1, value);
    }
    return -1;
    
}

Maybe I should change the logic return binarySearch(foodlist, high, mid+1, value);, but I have tried all possible combination, same out of bound error is thrown or not found for valid elements is displayed.

Any help would be much appreciated, Thanks


Solution

  • You have a logical error in your code

    change this

    return binarySearch(foodlist, high, mid + 1, value);
    

    to this

    return binarySearch(foodlist, mid + 1, high, value);