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?
To correct this error, check the search method's return value before iterating the array, as shown in this example. using System; using System. Collections. Generic; public class Example { static List<int> numbers = new List<int>(); public static void Main() { int startValue; string[] args = Environment.
YES. If the exception was inside a try then code inside matching catch blocks or finally block will be executed.
As to which is more correct? As Kirk's comment suggests: it depends. Sometimes a null
makes logical sense and sometimes an exception is better suited if no default is reasonable. One thing I try to do is think of "is calling GetCurrentItem
a logical failure or a safe thing?"
If it is a failure to call GetCurrentItem
when there are none, then throwing an exception is the correct course. For example, if your collection has a HasCurrent
or IsEmpty
property where someone could examine the result before calling GetCurrentItem
, then they should "know better". But if the current item is null
is 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 ArgumentOutOfRange
exception may be bleeding implementation details. That is, if the user of this class has no idea that the inner structure is an array or List<T>
, then don't bleed out that exception, but catch it, wrap it, and throw a more meaningful one (custom, or something like InvalidOperationException
).
Since they're not really directly passing in an argument, them getting an ArgumentOutOfRange
exception could be confusing :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With