Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

ClassCastException?

like image 548
ritch Avatar asked May 03 '12 11:05

ritch


2 Answers

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?

like image 84
adarshr Avatar answered Sep 30 '22 11:09

adarshr


Unsurprisingly, the API docs specify the exception to be thrown in this case.

ClassCastException - if the specified object's type prevents it from being compared to this object.

Assuming you are using generics, you will automatically get this exception if someone attempts to call your methods using raw types, reflections or some other unsafe technique.

like image 22
Tom Hawtin - tackline Avatar answered Sep 30 '22 11:09

Tom Hawtin - tackline