I have the following scenario:
If not what is the most graceful way to deal with this exception. I have a throw new notimplementedexception but I think there is a more elegant way.
Code is:
foreach (SPContentType type in sPContentTypeCollection)
{
if (type.Name == contentTypeName)
{
return type;
}
}
throw new NotImplementedException();
As you can see, it's not what I would call readable code. How can I make it easier for the next guy to maintain. On a side note, it does what it should from a technical perspective.
Well NotImplementedException
is certainly inappropriate, because you have implemented the method... but what sort of exception should you throw? It really depends on the context, to be honest.
Sometimes it would be appropriate to return null to indicate a missing value. Other times, throwing an exception is fine - possibly an InvalidOperationException
for example. You should throw an exception if this situation represents an error of some description, rather than it being a perfectly reasonable situation which the caller should expect to occur.
As for the rest of the code... if you're using .NET 3.5 you could just use LINQ:
return sPContentTypeCollection.Cast<SPContentType>()
.First(type => type.Name == contentTypeName);
That will throw an InvalidOperationException
for you automatically if the name isn't found. Or if you want to return null:
// type shortened to t to avoid scrollbars...
return sPContentTypeCollection.Cast<SPContentType>()
.FirstOrDefault(t => t.Name == contentTypeName);
It really depends on whether this is an expected or exceptional case.
If the item you compare with is passed to a method and there really always should be a matching item in the collection I'd throw an ArgumentOutOfRangeException
exception.
If it is expected that sometimes no matching item is found, I would just return null
to indicate that the requested item was not found.
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