jamesdeath123 jamesdeath123 - 7 months ago 22
Java Question

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?

Answer

Make DependencyFailureException a runtime exception or surround your return in a try catch block.

public class GraphEdge implements Comparable {

    public abstract double getLength() throws DependencyFailureException;

    @Override
    public int compareTo(Object obj) {
            try {
               return getLength().compareTo(((GraphEdge)obj).getLength()));
            } catch (RuntimeException ex) {
                 throw ex;
            } catch (DependencyFailureException ex) {
                 return -1; // or appropriate error value
            }
    }
}