You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

二分查找未捕获ArrayIndexOutOfBoundsException异常问题求助

问题分析与修复方案

核心问题

你的二分查找方法存在两个关键错误:

  • 递归搜索右半区间时参数传递错误,直接导致数组索引越界
  • 用ArrayIndexOutOfBoundsException处理元素不存在的逻辑不合理,且该异常实际在二分查找过程中抛出,并未被try-catch捕获

错误点详解

  1. 递归参数错误:
    当目标值大于foodlist[mid].id时,需要搜索mid+1到high的右半区间,但代码错误地将low设为high、high设为mid+1:
return binarySearch(foodlist, high, mid+1, value);

这会导致递归过程中high不断超出数组最大索引(foodlist.length-1),最终访问foodlist[mid]时触发ArrayIndexOutOfBoundsException。

  1. 异常使用错误:
    ArrayIndexOutOfBoundsException是表示数组索引越界的运行时异常,不应该用来表示“元素未找到”的业务逻辑。而且你的try-catch块在调用完二分查找后才执行,异常在二分查找过程中抛出,根本没进入try块,所以无法被捕获。

修复后的代码

修正二分查找方法

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 
            // 目标值更大,搜索右半区间:low设为mid+1,high保持不变
            return binarySearch(foodlist, mid+1, high, value);
    }
    // 未找到元素,返回-1
    return -1;
}

修正主逻辑(移除不合理的异常抛出)

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

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

额外说明

  • 二分查找的前提是数组已经按id升序排序,如果数组未排序,二分查找会失效,需要先确保数组有序。
  • 不要用系统异常处理业务逻辑,直接通过返回值(如-1)判断元素是否存在更清晰、更符合规范。

内容的提问来源于stack exchange,提问作者raj_b

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 19:15:50