抛出异常或阻止它?

Emz*_*Emz 3 java exception-handling

现在的问题是,如果它是首选,以Throw一个exception或防止它不断发生.这是一个游戏项目.

IndexOutOfBoundsException 与编码相关.

我有一个 List<E>

private Attribute<List> attributes;
Run Code Online (Sandbox Code Playgroud)

一种通过索引获取项目的方法.

public Attribute getAttribute (int index) {
    if (index < 0 || index >= attributes.size())
        index = 0;

    return attributes.get(index);
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我默认为列表的第一个元素.

ass*_*ias 8

快速失败通常是一个好主意:如果将-1的索引传递给该方法,则可能意味着调用该方法的代码中存在错误.如果您默默使用index = 0,(a)调用代码可能无法收到预期的结果,(b)您可能不会注意到该错误,直到它变得非常混乱.

所以我只想使用:

public Attribute getAttribute (int index) {
    return attributes.get(index);
}
Run Code Online (Sandbox Code Playgroud)

如果需要,将抛出异常.如果调用此方法的代码没有错误,则永远不应抛出该异常.