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

Exception执行问题:为何catch代码块未被触发?

问题分析与解决

你的catch块没执行的核心原因很简单:try代码块里根本没抛出NoSuchElementException异常。

你原本以为contains(value) == true不成立时会触发异常,但你的代码里完全没有这个逻辑——当contains(value)返回false时,try块里什么都不会执行,自然不会抛出任何异常,catch块也就没有触发的机会。

代码问题拆解

看你的代码逻辑:

@Override
public void remove(int value) throws NoSuchElementException {
    ListItem index = head;
    System.out.println("value " + value);
    try {
        // 只有contains返回true时才会进入这个分支执行逻辑
        if (contains(value) == true) {
            // ... 移除元素的逻辑
        }
        // contains返回false时,这里什么都不做,也没抛异常
    } catch (NoSuchElementException e) {
        System.out.println("HEllo");
        throw new NoSuchElementException("No such Element.");
    }
}

当contains(value)为false时,try块内不会执行任何代码,也没有抛出异常的语句,catch块当然不会被触发。

修复方法

要实现你预期的逻辑(元素不存在时触发catch块),需要在contains(value)为false时,手动抛出NoSuchElementException,这样try块才会产生异常,catch才能捕获:

@Override
public void remove(int value) throws NoSuchElementException {
    ListItem index = head;
    System.out.println("value " + value);
    try {
        if (contains(value)) { // 可简化为contains(value),无需==true
            System.out.println("Nö");
            if (head == tail) {
                tail = null;
            } else if (head.value == value) {
                head = head.next;
            }
            while ((index.next != null) && (index.next.value != value)) {
                index = index.next;
            }
            if (index.next == null) {
                index = null;
            } else if (index.next.value == value) {
                index.next = index.next.next;
            }
        } else {
            // 元素不存在时手动抛出异常
            throw new NoSuchElementException();
        }
    } catch (NoSuchElementException e) {
        System.out.println("HEllo");
        throw new NoSuchElementException("No such Element.");
    }
}

额外补充:这个方法本身已经声明了throws NoSuchElementException,如果不需要在catch里做打印操作,也可以直接在else分支抛出异常,去掉try-catch包裹,代码会更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 04:00:52