11

I'm making a custom class that implements comparable, and I'd like to throw some kind of exception if somebody tries to compare two objects that are not comparable by my definition. Is there a suitable exception already in the API, or do I need to make my own?

Mirrana
  • 1,601
  • 6
  • 28
  • 66

2 Answers2

9

Not that I know of.

The most accurate Exception to represent this is probably an IllegalArgumentException: http://docs.oracle.com/javase/7/docs/api/java/lang/IllegalArgumentException.html

You should probably also be implementing Comparable<CustomClass> which will prevent callers from providing an instance of the wrong class.

Cory Kendall
  • 7,195
  • 8
  • 37
  • 64
2

Consider ClassCastException, it is what Java Collection Framework throws for such situations. This is what happens when we try to add a non-comparable Test1 to a TreeSet

Exception in thread "main" java.lang.ClassCastException: Test1 cannot be cast to java.lang.Comparable
    at java.util.TreeMap.compare(TreeMap.java:1188)
    at java.util.TreeMap.put(TreeMap.java:531)
    at java.util.TreeSet.add(TreeSet.java:255)
    at java.util.AbstractCollection.addAll(AbstractCollection.java:334)
    at java.util.TreeSet.addAll(TreeSet.java:312)
    at java.util.TreeSet.<init>(TreeSet.java:160)
    at Test1.main(Test1.java:9)
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • +1 for ClassCastException. This is referenced in the compareTo javadoc: https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html#compareTo-T-. But ideally, as Cory Kendall says above, you should try to come up with a class hierarchy that prevents this. – philo Mar 17 '17 at 17:40