gpt4 book ai didi

java - 在 IndexOutOfBoundsException 异常时返回什么?

转载 作者:搜寻专家 更新时间:2023-11-01 00:59:14 25 4
gpt4 key购买 nike

我有以下方法

private ArrayList<User> allUsers = new ArrayList<User>();

public User getUser(int index) {
try {
return allUsers.get(index);
}
catch(IndexOutOfBoundsException e) {
// What should I return here?? Say that you want index 0 and no User
// exists in the ArrayList allUsers, what should I then return? The
// method needs a User to be returned
}
}

而且我不确定在这里该怎么做,我确信这是一个简单的解决方法,但是我应该在 catch block 中返回什么? Eclipse 提示必须返回一个 User

最佳答案

我的一般意见是,您不应该永远不要捕获您不知道如何处理的异常。特别是在这种情况下,由于 IndexOutOfBoundsException 是一个 RuntimeException,因此不需要被捕获 - 您也可以让它向上传播调用堆栈。调用者通过列表索引请求一个对象,因此大概知道要请求哪个索引——然后,抛出或允许抛出的 IndexOutOfBoundsException 传播似乎非常自然。

唯一其他明显的选择是吞下异常并返回 null,但我真的不喜欢这种方法,因为在没有明智的情况下,调用方会出现这种明显的错误返回值。您还可以返回一个特殊的 User 实例(引用 null object pattern),但即使这样也不能免除调用者检查返回内容的责任。根据 User 的接口(interface)和实现,此类检查可能微不足道,但仍需要在某处完成。

如果你想明确该方法可以抛出异常,就这么说:

public User getUser(int index) throws IndexOutOfBoundsException { ... }

或点赞@ Bela Vizer建议,将其包装在 IllegalArgumentException(这也是一个 RuntimeException)中。

正如@ lc. 指出的那样,最好先自己检查对象是否存在,然后再尝试访问它。自己处理您预期 的错误情况,而不是依赖 get() 方法调用来抛出异常。您仍然应该清楚方法可能会抛出这样的异常,但是,如果集合在检查和返回之间被修改。对于多核 CPU 上的多线程软件,已知会发生奇怪的事情。

关于java - 在 IndexOutOfBoundsException 异常时返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13433438/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com