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.
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.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?
The general rule of thumb is to avoid using exceptions for control flow unless the circumstances that will trigger the exception are "exceptional" -- e.g., extremely rare!
If this is something that will happen normally and regularly it definitely should not be handled as an exception.
Exceptions are very, very slow due to all the overhead involved, so there can be performance reasons as well, if it's happening often enough.
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:
It is important that exceptions are thrown only when an unexpected or invalid activity occurs that prevents a method from completing its normal function. Exception handling introduces a small overhead and lowers performance so should not be used for normal program flow instead of conditional processing. It can also be difficult to maintain code that misuses exception handling in this way.
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