I have the following scenario:
- I have a foreach loop that loops through a collection, if an item is found (based on criteria as in example below), it will return that item.
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
NotImplementedExceptionis 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
InvalidOperationExceptionfor 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:
That will throw an
InvalidOperationExceptionfor you automatically if the name isn’t found. Or if you want to return null: