简体   繁体   中英

method that throws exception that calls another method that throws a different exception (java)

TreeInter is an interface with methods, including maximum(). In MapClass, I am trying to use EmptyTreeClass' maximum() to write maximumKey() which returns largest key in object map. However, the two methods throw two different exceptions. If maximimum() catches an exception, the tree remains unchanged. I'm kind of confused how to write maximumKey() despite knowing that I need to use maximum(). Would I need to catch both exceptions in the method?

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
        }       

您尚未在MapClass中声明root,因此以下行将无法编译:

return root;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM