I have seen the following exception case several times
public SomeClass(IEnumerable<T> someValues)
{
if (null == someValues)
{
throw new ArgumentNullException("someValues");
}
int counter = 0;
foreach (T value in someValues)
{
if (null == value)
{
string msg = counter + "th value was null";
// What exception class to use?
throw new ArgumentException(msg, "someValues");
}
counter++;
}
}
Is there a guideline for handling these cases? And in general is there any guidelines describing "exception style" a bit more detailed than the MSDN documentation for
An object collection such as an IEnumerable<T> can contain elements whose value is null.
The returned IEnumerable<> might be empty, but it will never be null .
Clear() will empty out an existing IEnumerable. model. Categories = new IEnumerable<whatever>() will create a new empty one. It may not be a nullable type - that would explain why it can't be set to null.
Throw ArgumentNullException if there was a null argument.
Throw ArgumentOutOfRange exception if there was an argument out of its range (like a negative number where only positive numbers were expected.)
Throw ArgumentException if the argument was invalid for a reason other than it was out of range or null.
Throw InvalidOperationException if the call was invalid for a reason not pertaining specifically to a value of an argument.
In this particular case I'd probably choose ArgumentException. The argument is invalid because its contents are invalid.
Of course, all of these are exceptions which indicate that the caller has a bug. It's a good habit to give the best possible error so that the author of the buggy caller can rapidly diagnose the problem. I'd therefore consider also adding a custom message to the exception saying "element of sequence blah was unexpectedly null" or some such thing.
Yes there is, as described here, you should throw framework exceptions when possible and throwing the most derived exception that is applicable. In this case ArgumentNullException
is thrown because an argument is null and ArgumentException
is thrown because the contents of the enumeration are not directly a parameter of the function, so what you can say is that the argument is invalid, but it is not because it i null or is out of range.
If knowing why it is invalid becomes absolutely necessary you could derive from Argument Exception
; something like ArgumentCollectionContainsNullException
.
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