Java overrides compareTo with exception handling

Suppose 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());
    }
}

Don't worry about checking the obj type in compareTo for now. getLength () throws a DependencyFailureException if its dependency does not work. Because getLength () throws an exception, compareTo gives a compile-time error because the DependencyFailureException is not thrown.

I donโ€™t know if try / catch can do this best, as if an exception occurred in getLength (), which means that the length of this edge no longer makes sense and comparing it with another double does not help. I think if the exception came from getLength (), it should just get the surface at the top of the hirachey call.

DependencyFailureException is a custom exception that I can change if necessary.

What to do to match GraphEdge?

+4
source share
3 answers

As mentioned above, you can just wrap it in an Unchecked exception, and this 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;
}
+2
source

Make DependencyFailureException exception runtime or delay his return to 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
            }
    }
}
+1
source

(, , ), :

      "declare any new checked exceptions for an implementation method".

, , compareTo.

0

All Articles