title: VB.NET Selection of item by key inside collection: Try ... Catch vs. For Each
body: <p>I'm just wondering what would be the best programming technique for selecting an item inside of a collection by string (or key). To cut the story short, here the two sample codes:</p>
  
  <p>Code (1): Try ... Catch</p>
  
  <pre class="lang-vb prettyprint-override"><code>Sub TryCatchExample()
    ' Define the objects ...
    Dim col_List As Collection
    Dim label_Item As Windows.Forms.Label
    Dim object_Result As Object
  
    ' Assign something to the collection ...
    label_Item = New Windows.Forms.Label
    label_Item.Name = "Label_1"
    col_List.Add(label_Item, label_Item.Name)
  
    ' Now try to find "Label_2" by using Item property with key string ...
    Try
        object_Result = col_List.Item("Label_2")
        ' Do something if available ...
    Catch ex As Exception
        ' We can look up for the reason of error, 
        ' but for this example we will skip this.
        ' Couldn't find "Label_2" ...
        Debug.Print("Couldn't find your requested object by string: 'Label_2'")
    End Try
  End Sub
  </code></pre>
  
  <p>Code (2): For ... Each</p>
  
  <pre class="lang-vb prettyprint-override"><code>Sub ForEachExample()
    ' Define the objects ...
    Dim col_List As Collection
    Dim label_Item As Windows.Forms.Label
    Dim object_Result As Object
  
    ' Assign something to the collection ...
    label_Item = New Windows.Forms.Label
    label_Item.Name = "Label_1"
    col_List.Add(label_Item, label_Item.Name)
  
    ' Now try to find "Label_2" by browsing through collection ...
    For Each object_Item As Object In col_List
        If object_Item.Name = "Label_2" Then
            object_Result = object_Item
        End If
    Next
  
    ' Now we have to check if there is an object available ...
    If object_Item Is Nothing Then
        Debug.Print("Couldn't find your requested object by string: 'Label_2'")
    End If
  End Sub
  </code></pre>
  
  <p>For code (1) we have to run into an error to discover that "Label_2" key isn't available. For code (2) we have to write some more lines, but it will do the same. </p>
  
  <p>Now the question: <em>What's the better way to do?</em></p>