简体   繁体   English

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

[英]method that throws exception that calls another method that throws a different exception (java)

TreeInter is an interface with methods, including maximum(). TreeInter是具有方法的接口,包括max()。 In MapClass, I am trying to use EmptyTreeClass' maximum() to write maximumKey() which returns largest key in object map. 在MapClass中,我尝试使用EmptyTreeClass的maximum()编写maximumKey(),该方法返回对象映射中的最大键。 However, the two methods throw two different exceptions. 但是,这两种方法会引发两个不同的异常。 If maximimum() catches an exception, the tree remains unchanged. 如果maximimum()捕获异常,则树保持不变。 I'm kind of confused how to write maximumKey() despite knowing that I need to use maximum(). 尽管知道我需要使用maximum(),但我对如何编写maximumKey()感到困惑。 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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