抛出异常的方法,该异常调用另一个抛出不同异常的方法(java)

时间:2014-11-08 22:06:49

标签: java exception map tree try-catch

TreeInter是一个包含maximum()方法的接口。在MapClass中,我试图使用EmptyTreeClass' maximum()写入maximumKey(),它返回对象映射中的最大键。但是,这两种方法抛出了两个不同的例外。如果maximimum()捕获异常,则树保持不变。尽管知道我需要使用maximum(),但我有点困惑如何编写maximumKey()。我需要在方法中捕获两个异常吗?

public class UnemptyTreeClass<Key, Value> implements TreeInter<Key, Value> {
    private Key root;
    private Value value;
    private Tree<Key, Value> left, right;

public Key maximum() throws EmptyTreeException {
        try {
            return right.max();
        } catch (EmptyTreeException e) {
            return root;
        }
    }

public class EmptyTreeClass<Key, Value> implements TreeInter<Key, Value> {
    private static EmptyTree emptytree = new EmptyTree();

    public static EmptyTree getInstance() {
        return emptytree;
    }

public Key maximum() throws EmptyTreeException {
        throw new EmptyTreeException();
    }

public class MapClass<Key, Value> {
    Tree<Key,Value> instance= EmptyTree.getInstance();

public Key maximumKey() throws NoSuchElementException{

if (instance==EmptyTree.getInstance())
            throw new NoSuchElementException();
        try {
            return instance.maximum();
        } catch (EmptyTreeException e) {
            return root; //error here
        }       

1 个答案:

答案 0 :(得分:0)

您尚未在MapClass中声明root,因此以下行不会编译:

return root;