Imagine an object you are working with has a collection of other objects associated with it, for example, the Controls collection on a WinForm. You want to check for a certain object in the collection, but the collection doesn’t have a Contains() method. There are several ways of dealing with this.
- Implement your own
Contains()method by looping through all items in the collection to see if one of them is what you are looking for. This seems to be the ‘best practice’ approach. - I recently came across some code where instead of a loop, there was an attempt to access the object inside a try statement, as follows:
try { Object aObject = myCollection[myObject]; } catch(Exception e) { //if this is thrown, then the object doesn't exist in the collection }
My question is how poor of a programming practice do you consider the second option be and why? How is the performance of it compared to a loop through the collection?
I would have to say that this is pretty bad practice. Whilst some people might be happy to say that looping through the collection is less efficient to throwing an exception, there is an overhead to throwing an exception. I would also question why you are using a collection to access an item by key when you would be better suited to using a dictionary or hashtable.
My main problem with this code however, is that regardless of the type of exception thrown, you are always going to be left with the same result.
For example, an exception could be thrown because the object doesn’t exist in the collection, or because the collection itself is null or because you can’t cast myCollect[myObject] to aObject.
All of these exceptions will get handled in the same way, which may not be your intention.
These are a couple of nice articles on when and where it is usally considered acceptable to throw exceptions:
I particularly like this quote from the second article: