I have a class containing a collection of items. For convenience I’ve provided GetCurrentItem which is implemented by
public Type GetCurrentItem
{
get { return this.items[this.items.Count - 1]; }
}
which will throw an exception if there are no items in the list.
Should I let the exception be thrown or should I return null? If this was an API I handed to you, what would you expect? The exception or null? Is there a better way to handle this?
As to which is more correct? As Kirk’s comment suggests: it depends. Sometimes a
nullmakes logical sense and sometimes an exception is better suited if no default is reasonable. One thing I try to do is think of “is callingGetCurrentItema logical failure or a safe thing?”If it is a failure to call
GetCurrentItemwhen there are none, then throwing an exception is the correct course. For example, if your collection has aHasCurrentorIsEmptyproperty where someone could examine the result before callingGetCurrentItem, then they should “know better”. But if the current item isnullis a correct logical way of using your class, then by all means design it that way. Either way, I’d document the behavior in the code comments to let users know of expected behavior.I will say this though, exposing the
ArgumentOutOfRangeexception may be bleeding implementation details. That is, if the user of this class has no idea that the inner structure is an array orList<T>, then don’t bleed out that exception, but catch it, wrap it, and throw a more meaningful one (custom, or something likeInvalidOperationException).Since they’re not really directly passing in an argument, them getting an
ArgumentOutOfRangeexception could be confusing 🙂