Using unhandled exceptions instead of Contains()?

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:

  • Foundations of Programming
  • Throwing exceptions in c#

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.