Search code examples
javaoverridingcomparable

Java overriding compareTo with exception handling


Assume I have this class:

public abstract class GraphEdge implements Comparable {

    public abstract double getLength() throws DependencyFailureException;

    @Override
    public int compareTo(Object obj) {
        return Double.compare(getLength(), ((GraphEdge)obj).getLength());
    }
}

Let's not worry about checking the type of obj in compareTo at this moment. getLength() is throwing the exception DependencyFailureException if its dependency is failing. Since getLength() throws an exception, compareTo is giving compile time error as the DependencyFailureException is unhandled.

I don't know if try/catch is the best thing I can do here, as if the exception happened in the getLength(), that means the length of this edge is not meaningful any more and comparing it to another double is not helping. I think if exception happened from getLength(), it should just get surface to the top of the call hirachey.

DependencyFailureException is an custom exception that I can change, if necessary.

What should I do to make the GraphEdge comparable?


Solution

  • As mentioned above you can simply wrap it up in Unchecked exception and that will work for you.

    @Override
    public int compareTo(Object o) {
    
        try {
            return getLength().compareTo(((GraphEdge)obj).getLength()));
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        return 0;
    }