Is it safe to hide the ClassCastException class when reading a specific value?

Suppose I implement a sorted collection (a simple example is 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(); Arrays.sort(this.array, this.comparator); } @Override public boolean contains(Object key) { return Arrays.binarySearch(array, key, comparator) >= 0; } private final Object[] array; private final Comparator<Object> comparator; } 

Now create a set of integers

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

And check if it contains 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 ClassCastException . Not what I want. I would prefer it to return false (as the HashSet does.)

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

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

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

+4
source share
3 answers

I don’t think there is a problem with this, because the Javadoc for Collection.contains clearly states that ClassCastException not necessary to throw a ClassCastException .

The only problem I see is that if you have an error, not throwing an exception somewhere will not allow you to identify it.

+3
source

The TreeSet class TreeSet a ClassCastException for incompatible contains() arguments (incompatible for the Comparator used by the set). Therefore, there is nothing wrong with throwing this exception. Just make sure you confirm that this can happen.

+1
source

It is perfectly legal to allow the release of CCE from contains (). However, many implementations of the collection catch this and return false, which I also consider quite legal, and in fact this is a more convenient behavior.

In equals () you have no choice; you have to catch this cce.

Eliminating an uncontrolled exception should always be dirty, but sometimes it’s right.

+1
source

Source: https://habr.com/ru/post/1335321/


All Articles