[英]method that throws exception that calls another method that throws a different exception (java)
TreeInter是具有方法的接口,包括max()。 在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
}
您尚未在MapClass中聲明root,因此以下行將無法編譯:
return root;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.