Throw Exception or prevent it?

北城余情 提交于 2019-12-10 21:17:21

问题


The question is if it is prefered to Throw an exception or to prevent it from ever occurring. It is for a game project.

IndexOutOfBoundsException vs. coding around it.

I have a List<E>

private Attribute<List> attributes;

A method to get an item by index.

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

    return attributes.get(index);
}

In this case I am defaulting to the 1st element of the list.


回答1:


Failing fast is generally a good idea: if an index of -1 is passed to that method, it probably means that there is a bug in the code calling the method. If you silently use index = 0 instead, (a) the calling code may not receive the expected result and (b) you may not notice the bug until it has become quite a mess to fix.

So I would simply use:

public Attribute getAttribute (int index) {
    return attributes.get(index);
}

which will throw an exception if required. If the code calling this method is bug free, that exception should never be thrown.




回答2:


In this case, pretending that an index exists and is the same element as the first element is confusing and can lead to subtle bugs.

Here I would throw an IndexOutOfBoundsException if the index is out of range. Note that other code that calls this must be prepared to catch this exception and handle it appropriately.




回答3:


The answer is highly situational. In general, you want to handle exceptions elegantly whenever possible. That is, try to resolve / ignore them where you can. An IndexOutOfBoundsException is very often an example of where this is not possible.

Hard breaks because of exceptions is a last-resort. Do this only when your program cannot continue.

This question's answer has a good post on it. When to throw an exception?



来源:https://stackoverflow.com/questions/27157206/throw-exception-or-prevent-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!