抛出异常还是阻止它? [英] Throw Exception or prevent it?
问题描述
问题是如果它优先于抛出
一个异常
或阻止它发生。这是一个游戏项目。
IndexOutOfBoundsException
与其编码。
我有一个列表< E>
私有属性<列表>属性;
按索引获取项目的方法。
公共属性getAttribute(int index){
if(index< 0 || index> = attributes.size())
index = 0;
return attributes.get(index);
}
在这种情况下,我默认为列表的第1个元素。 p>
失败一般是一个好主意:如果-1的索引传递给该方法,那可能意味着有一个代码调用方法的bug。如果您默认使用index = 0,(a)调用代码可能不会收到预期的结果,(b)您可能不会注意到这个错误,直到它变得相当麻烦来修复。
所以我只需使用:
public Attribute getAttribute(int index){
return attributes获得(索引);
}
如果需要,将抛出异常。如果调用此方法的代码是无错误的,则不应抛出该异常。
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.
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.
这篇关于抛出异常还是阻止它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!