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

如何在ArrayList中元素不存在时抛出自定义Data Exception?

解决自定义索引越界异常的问题

嘿,我来帮你搞定这个问题!首先得明确:你原来的if语句没生效,大概率是校验时机不对或者条件写反了——咱们得在调用ArrayList.get()之前就主动检查索引合法性,而不是等系统抛出异常再处理。下面一步步来实现:

1. 先创建自定义的DataException类

首先得有自己的异常类,它需要继承Exception(受检异常,必须显式处理)或者RuntimeException(非受检异常,不用强制处理)。推荐用受检异常,这样调用方必须处理异常,代码更规范:

public class DataException extends Exception {
    // 带错误信息的构造方法
    public DataException(String message) {
        super(message);
    }
}

2. 主动校验索引,抛出自定义异常

核心逻辑是:在获取元素前,先判断索引是否在合法范围内(0 ≤ 索引 < 列表长度)。如果不在,直接抛你的DataException;如果合法,再调用get()方法。

举个完整的示例代码:

import java.util.ArrayList;
import java.util.Scanner;

public class ListElementAccessor {
    public static void main(String[] args) {
        // 初始化测试列表
        ArrayList<String> stringList = new ArrayList<>();
        stringList.add("Java");
        stringList.add("Python");
        stringList.add("C++");

        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入要访问的索引:");
        int inputIndex = scanner.nextInt();

        try {
            String targetElement = getElement(stringList, inputIndex);
            System.out.println("获取到的元素:" + targetElement);
        } catch (DataException e) {
            // 处理自定义异常
            System.err.println("错误提示:" + e.getMessage());
        }
    }

    // 自定义方法:获取指定索引的元素,索引非法则抛DataException
    public static String getElement(ArrayList<String> list, int index) throws DataException {
        // 关键:这里的判断条件是索引越界的情况
        if (index < 0 || index >= list.size()) {
            throw new DataException("索引 " + index + " 无效!当前列表有效索引范围是 0 到 " + (list.size() - 1));
        }
        // 索引合法才调用get()
        return list.get(index);
    }
}

为什么你原来的if没生效?

大概率是这两个原因:

  • 校验时机错了:你可能是先调用了list.get(index),再用if判断——这时候系统已经抛出IndexOutOfBoundsException了,你的if根本没机会执行。
  • 条件写反了:比如你写成了if (index >=0 && index < list.size())然后抛异常,这显然搞反了,只有索引合法的时候才抛,肯定不对。

额外注意点

如果不想用受检异常,把DataException改成继承RuntimeException就行,这样方法签名里不用加throws DataException,调用方也可以不用try-catch(但建议还是处理,避免程序崩溃)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:23:09