Is it safe to silently catch ClassCastException when searching for a specific value?

Posted by finnw on Stack Overflow See other posts from Stack Overflow or by finnw
Published on 2011-01-12T22:07:41Z Indexed on 2011/01/12 22:53 UTC
Read the original article Hit count: 263

Suppose I am implementing a sorted collection (simple example - a Set based on a sorted array.) Consider this (incomplete) implementation:

import java.util.*;

public class SortedArraySet<E> extends AbstractSet<E> {

    @SuppressWarnings("unchecked")
    public SortedArraySet(Collection<E> source, Comparator<E> comparator) {
        this.comparator = (Comparator<Object>) comparator;
        this.array = source.toArray();
        Collections.sort(Arrays.asList(array), this.comparator);
    }

    @Override    
    public boolean contains(Object key) {
        return Collections.binarySearch(Arrays.asList(array), key, comparator) >= 0;
    }

    private final Object[] array;

    private final Comparator<Object> comparator;

}

Now let's create a set of integers

Set<Integer> s = new SortedArraySet<Integer>(Arrays.asList(1, 2, 3), null);

And test whether it contains some specific values:

System.out.println(s.contains(2));
System.out.println(s.contains(42));
System.out.println(s.contains("42"));

The third line above will throw a ClassCastException. Not what I want. I would prefer it to return false (as HashSet does.)

I can get this behaviour by catching the exception and returning false:

@Override    
public boolean contains(Object key) {
    try {
        return Collections.binarySearch(Arrays.asList(array), key, comparator) >= 0;
    } catch (ClassCastException e) {
        return false;
    }
}

Assuming the source collection is correctly typed, what could go wrong if I do this?

© Stack Overflow or respective owner

Related posts about java

Related posts about collections