title: Is it safe to silently catch ClassCastException when searching for a specific value?
body: <p>Suppose I am implementing a sorted collection (simple example - a <code>Set</code> based on a sorted array.)  Consider this (incomplete) implementation:</p>
  
  <pre><code>import java.util.*;
  
  public class SortedArraySet&lt;E&gt; extends AbstractSet&lt;E&gt; {
  
      @SuppressWarnings("unchecked")
  public SortedArraySet(Collection&lt;E&gt; source, Comparator&lt;E&gt; comparator) {
      this.comparator = (Comparator&lt;Object&gt;) comparator;
      this.array = source.toArray();
      Arrays.sort(this.array, this.comparator);
  }
  
  @Override
  public boolean contains(Object key) {
      return Arrays.binarySearch(array, key, comparator) &gt;= 0;
  }
  
      private final Object[] array;
  
      private final Comparator&lt;Object&gt; comparator;
  
  }
  </code></pre>
  
  <p>Now let's create a set of integers</p>
  
  <pre><code>Set&lt;Integer&gt; s = new SortedArraySet&lt;Integer&gt;(Arrays.asList(1, 2, 3), null);
  </code></pre>
  
  <p>And test whether it contains some specific values:</p>
  
  <pre><code>System.out.println(s.contains(2));
  System.out.println(s.contains(42));
  System.out.println(s.contains("42"));
  </code></pre>
  
  <p>The third line above will throw a <code>ClassCastException</code>.  Not what I want.  I would prefer it to return <code>false</code> (as <code>HashSet</code> does.)</p>
  
  <p>I can get this behaviour by catching the exception and returning false:</p>
  
  <pre><code>@Override    
  public boolean contains(Object key) {
      try {
          return Arrays.binarySearch(array, key, comparator) &gt;= 0;
      } catch (ClassCastException e) {
          return false;
      }
  }
  </code></pre>
  
  <p><em>Assuming the <code>source</code> collection is correctly typed</em>, what could go wrong if I do this?</p>