<p>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 <code>Contains()</code> method.  There are several ways of dealing with this.</p>

<ul>
<li>Implement your own <code>Contains()</code> 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.</li>
<li>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:</li>
</ul>

<blockquote>
<pre><code>try  
{  
    Object aObject = myCollection[myObject];  
}  
catch(Exception e)  
{  
    //if this is thrown, then the object doesn't exist in the collection
}
</code></pre>
</blockquote>

<p>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?</p>

[{'answer_id': 8350, 'author': 'Ryan Fox', 'author_id': 55, 'author_profile': 'https://Stackoverflow.com/users/55', 'pm_score': 0, 'selected': False, 'text': "<p>If, while writing your code, you expect this object to be in the collection, and then during runtime you find that it isn't, I would call that an exceptional case, and it is proper to use an exception.</p>\n\n<p>However, if you're simply testing for the existence of an object, and you find that it is not there, this is not exceptional. Using an exception in this case is not proper.</p>\n\n<p>The analysis of the runtime performance depends on the actual collection being used, and the method if searching for it. That shouldn't matter though. Don't let the illusion of optimization fool you into writing confusing code.</p>\n"}, {'answer_id': 8352, 'author': 'Patrick', 'author_id': 429, 'author_profile': 'https://Stackoverflow.com/users/429', 'pm_score': -1, 'selected': False, 'text': "<p>The latter is an acceptable solution. Although I would definitely catch on the specific exception (ElementNotFound?) that the collection throws in that case.</p>\n\n<p>Speedwise, it depends on the common case. If you're more likely to find the element than not, the exception solution will be faster. If you're more likely to fail, then it would depend on size of the collection and its iteration speed. Either way, you'd want to measure against normal use to see if this is actually a bottle neck before worrying about speed like this. Go for clarity first, and the latter solution is far more clear than the former.</p>\n"}, {'answer_id': 8356, 'author': 'Mike Stone', 'author_id': 122, 'author_profile': 'https://Stackoverflow.com/users/122', 'pm_score': 0, 'selected': False, 'text': "<p>I would have to think about it more as to how much I like it... my gut instinct is, eh, not so much...</p>\n\n<p>EDIT: Ryan Fox's comments on the exceptional case is perfect, I concur</p>\n\n<p>As for performance, it depends on the indexer on the collection.  C# lets you override the indexer operator, so if it is doing a for loop like the contains method you would write, then it will be just as slow (with maybe a few nanoseconds slower due to the try/catch... but nothing to worry about unless that code itself is within a huge loop).</p>\n\n<p>If the indexer is O(1) (or even O(log(n))... or anything faster than O(n)), then the try/catch solution would be faster of course.</p>\n\n<p>Also, I am assuming the indexer is throwing the exception, if it is returning null, you could of course just check for null and not use the try/catch.</p>\n"}, {'answer_id': 8359, 'author': 'OJ.', 'author_id': 611, 'author_profile': 'https://Stackoverflow.com/users/611', 'pm_score': 0, 'selected': False, 'text': "<p>In general, using exception handling for program flow and logic is bad practice. I personally feel that the latter option is unacceptable use of exceptions. Given the features of languages commonly used these days (such as Linq and lambdas in C# for example) there's no reason not to write your own Contains() method.</p>\n\n<p>As a final thought, these days most collections <em>do</em> have a contains method already. So I think for the most part this is a non-issue.</p>\n"}, {'answer_id': 8366, 'author': 'lomaxx', 'author_id': 493, 'author_profile': 'https://Stackoverflow.com/users/493', 'pm_score': 3, 'selected': True, 'text': '<p>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.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>All of these exceptions will get handled in the same way, which may not be your intention.</p>\n\n<p>These are a couple of nice articles on when and where it is usally considered acceptable to throw exceptions:</p>\n\n<ul>\n<li><a href="http://codebetter.com/blogs/karlseguin/archive/2008/05/29/foundations-of-programming-pt-8-back-to-basics-exceptions.aspx" rel="nofollow noreferrer">Foundations of Programming</a></li>\n<li><a href="http://www.blackwasp.co.uk/CSharpThrowingExceptions.aspx" rel="nofollow noreferrer">Throwing exceptions in c#</a></li>\n</ul>\n\n<p>I particularly like this quote from the second article:</p>\n\n<blockquote>\n  <p>It is important that exceptions are\n  thrown only when an unexpected or\n  invalid activity occurs that prevents\n  a method from completing its normal\n  function. Exception handling\n  introduces a small overhead and lowers\n  performance so should not be used for\n  normal program flow instead of\n  conditional processing. It can also be\n  difficult to maintain code that\n  misuses exception handling in this\n  way.</p>\n</blockquote>\n'}, {'answer_id': 8368, 'author': 'Jeff Atwood', 'author_id': 1, 'author_profile': 'https://Stackoverflow.com/users/1', 'pm_score': 2, 'selected': False, 'text': '<p>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!</p>\n\n<p>If this is something that will happen normally and regularly it definitely should not be handled as an exception.</p>\n\n<p>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.</p>\n'}, {'answer_id': 8410, 'author': 'Orion Edwards', 'author_id': 234, 'author_profile': 'https://Stackoverflow.com/users/234', 'pm_score': 0, 'selected': False, 'text': "<p>Exceptions should be exceptional.</p>\n\n<p>Something like 'The collection is missing because the database has fallen out from underneath it' is exceptional</p>\n\n<p>Something like 'the key is not present' is normal behaviour for a dictionary.</p>\n\n<p>For your specific example of a winforms Control collection, the <code>Controls</code> property has a <code>ContainsKey</code> method, which is what you're supposed to use.</p>\n\n<p>There's no <code>ContainsValue</code> because when dealing with dictionaries/hashtables, there's no fast way short of iterating through the entire collection, of checking if something is present, so you're really discouraged from doing that.</p>\n\n<p>As for WHY Exceptions should be exceptional, it's about 2 things</p>\n\n<ol>\n<li><p>Indicating what your code is trying to do. You want to have your code match what it is trying to achieve, as closely as possible, so it is readable and maintainable. Exception handling adds a bunch of extra cruft which gets in the way of this purpose</p></li>\n<li><p>Brevity of code. You want your code to do what it's doing in the most direct way, so it is readable and maintainable. Again, the cruft added by exception handling gets in the way of this.</p></li>\n</ol>\n"}, {'answer_id': 13650, 'author': 'Scott Dorman', 'author_id': 1559, 'author_profile': 'https://Stackoverflow.com/users/1559', 'pm_score': 0, 'selected': False, 'text': '<p>Take a look at this blog post from Krzystof: <a href="http://blogs.msdn.com/kcwalina/archive/2008/07/17/ExceptionalError.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/kcwalina/archive/2008/07/17/ExceptionalError.aspx</a></p>\n\n<p>Exceptions should be used for communicating error conditions, but they shouldn\'t be used as control logic (especially when there are far simpler ways to determine a condition, such as Contains).</p>\n\n<p>Part of the issue is that exceptions, while not expensive to <em>throw</em> are expensive to <em>catch</em> and all exceptions are caught at some point.</p>\n'}]
['https://Stackoverflow.com/questions/8348', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/940/']