Alex Rivera | Logout

What type of Exception should I throw if the wrong type of object is passed?

Asked 2012-05-03T11:38:09.127
15

What type of Exception should I throw if the wrong type of object is passed into my compareTo method?

ClassCastException?

Edit
Report

1 Answer

22

It would be IllegalArgumentException in a general sense when the passed in value is not the right one.

However, as @Tom's answer below suggests, it could also be a ClassCastException for incorrect types. However, I am yet to encounter user code that does this.

But more fundamentally, if you're using the compareTo with generics, it will be a compile time error.

Consider this:

public class Person implements Comparable<Person> {
    private String name;
    private int age;

    @Override
    public int compareTo(Person o) {
       return this.name.compareTo(o.name);
    }
}

Where do you see the possibility of a wrong type being passed in the above example?

answered 2012-05-03T11:39:39.153

Your Answer