【问题标题】:Throwing Exception Troubles抛出异常问题
【发布时间】:2017-10-04 09:05:54
【问题描述】:

我很难抛出 IllegalStateForMatrixException。如果有人可以帮助我,将不胜感激。这是我的教授告诉我要做的,但实际上我仍然遇到问题。这是他给我的小费...

当使用 0 个边调用 getNumberOfEdges 时应该引发 IllegalStateForMatrixException。 调用具有 0 个边的 getNumberOfEdges 时应引发 IllegalStateForMatrix。 您需要做的就是检查矩阵没有正值。如果它没有抛出 IllegalStateForMatrix 异常。

您还可以将布尔值设置为 false,并在调用 createMatrix 时将其设置为 true。这将是一种检查 createMatrix 是否在 addEdge 之前或之后调用的方法。然后签入 addEdge 就可以抛出异常了。

class AdjacencyGraph extends Graph {

private ArrayList nodes = new ArrayList();
private int noEdges = 0;

/**
 * Adjacency matrix.
 */
public int[][] adjM;

/**
 * Boolean set to false, should be set true in create matrix.
 */
private boolean b = false;

/**
 * Adjacency Matrix with integers.
 */
@Override
void createAdjacencyMatrix() {
    adjM = new int[nodes.size()][nodes.size()];
    int i;
    int j;
    for (i = 0; i < nodes.size(); i++) {
        for (j = 0; j < nodes.size(); j++) {
            adjM[i][j] = -1;
        }
        b = true;
    }
}

/**
 * Adds the node.
 *
 * @param nodeName
 */
@Override
@SuppressWarnings("unchecked")
void addNode(String nodeName) {
    nodes.add(nodeName);
}

/**
 * Adds the edge.
 *
 * @param fromNode
 * @param toNode
 * @param weight
 * @throws ElementNotFoundException
 * @throws IllegalStateForMatrixException
 */
@Override
void addEdge(String fromNode, String toNode, int weight)
        throws ElementNotFoundException, IllegalStateForMatrixException {
    {
        try {
            if ( b == false)
                throw new IllegalStateForMatrixException("Exception");
            int i;
            int j;
            for (i = 0; i < nodes.size(); i++) {
                if (nodes.get(i).equals(fromNode)) {
                    break;
                }
            }
            if (i == nodes.size()) {
                throw new ElementNotFoundException("Exception");
            }

            for (j = 0; j < nodes.size(); j++) {
                if (nodes.get(j).equals(toNode)) {
                    break;
                }
            }
            if (j == nodes.size()) {
                throw new ElementNotFoundException("Exception");
            }

            adjM[i][j] = weight;
            adjM[j][i] = weight;
            noEdges++;
        } 
        catch (ElementNotFoundException e) {
            System.out.println("Exception found");
        }
        catch (IllegalStateForMatrixException e) {
            System.out.println("Exception found");
        }
    }
}

/**
 * Returns the number of nodes.
 *
 * @return number of nodes
 */
@Override
int getNumberOfNodes() {
    return nodes.size();
}

/**
 * Returns the number of edges
 *
 * @return number of edges
 * @throws IllegalStateForMatrixException
 */
@Override
int getNumberOfEdges() throws IllegalStateForMatrixException {
    if (nodes.size() <= 0)
        throw new IllegalStateForMatrixException("Error");
    return noEdges;
}

/**
 * Returns the highest degree node.
 *
 * @return highest degree node.
 * @throws ElementNotFoundException
 * @throws IllegalStateForMatrixException
 */
@Override
public String getHighestDegreeNode()
        throws ElementNotFoundException, IllegalStateForMatrixException {

    int i;
    int ansIndex = 0;
    int j;
    int ansCount = 0;
    for (i = 0; i < nodes.size(); i++) {
        int k = 0;
        for (j = 0; j < nodes.size(); j++) {
            if (adjM[i][j] != -1) {
                k++;
            }
        }
        if (k > ansCount) {
            ansCount = k;
            ansIndex = i;
        }
    }
    return (String) nodes.get(ansIndex);
}

/**
 * Cost of the edge between nodes.
 *
 * @param fromNode
 * @param toNode
 * @return returns -1
 * @throws ElementNotFoundException
 * @throws IllegalStateForMatrixException
 */
@Override
int costOfEdgeBetween(String fromNode, String toNode)
        throws ElementNotFoundException, IllegalStateForMatrixException {
    try {
        int i;
        int j;
        for (i = 0; i < nodes.size(); i++) {
            if (nodes.get(i).equals(fromNode)) {
                break;
            }
        }
        if (i == nodes.size()) {
            throw new ElementNotFoundException("Exception");
        }

        for (j = 0; j < nodes.size(); j++) {
            if (nodes.get(j).equals(toNode)) {
                break;
            }
        }
        if (j == nodes.size()) {
            throw new ElementNotFoundException("Exception");
        }

        return adjM[i][j];
    } 
    catch (ElementNotFoundException e) {
        System.out.println("Exception found");
    }
    return -1;
}

/**
 *
 * @param fromName
 * @param toName
 * @return false
 * @throws ElementNotFoundException
 * @throws IllegalStateForMatrixException
 */
@Override
boolean hasPathBetween(String fromName, String toName)
        throws ElementNotFoundException, IllegalStateForMatrixException {
    try {
        ArrayStack<Integer> st = new ArrayStack<Integer>();
        int[] visited = new int[nodes.size()];
        int i;
        int j;
        int start;
        int end;
        for (i = 0; i < nodes.size(); i++) {
            visited[i] = 0;
        }

        for (i = 0; i < nodes.size(); i++) {
            if (nodes.get(i).equals(fromName)) {
                break;
            }
        }
        start = i;

        for (j = 0; j < nodes.size(); j++) {
            if (nodes.get(j).equals(toName)) {
                break;
            }
        }
        end = j;
        st.push(start);
        visited[start] = 1;
        while (st.isEmpty() != true) {
            i = st.pop();
            if (i == end) {
                return true;
            }
            for (j = 0; j < nodes.size(); j++) {
                if (adjM[i][j] != -1 && visited[j] == 0) {
                    visited[j] = 1;
                    st.push(j);
                }
            }
        }
        return false;
    } 
    catch (Exception e) {
        System.out.println("Exception found");
    }
    return false;
}

/**
 * The number of Isolated points
 *
 * @return ans
 * @throws IllegalStateForMatrixException
 */
@Override
int numIsolatedPoints() throws IllegalStateForMatrixException {
    int i;
    int j;
    int ans = 0;
    for (i = 0; i < nodes.size(); i++) {
        for (j = 0; j < nodes.size(); j++) {
            if (adjM[i][j] != -1) {
                break;
            }
        }
        if (j == nodes.size()) {
            ans++;
        }
    }
    return ans;
}

/**
 * Inclusiveness is the percentage of points in the graph that are not
 * isolated
 *
 * @return ((float)i)/nodes.size()
 * @throws IllegalStateForMatrixException
 */
@Override
float inclusiveness() throws IllegalStateForMatrixException {
    int i = nodes.size() - numIsolatedPoints();
    return ((float) i) / nodes.size();
}

/**
 * Density of matrix
 *
 * @return (2*(float)noEdges)/(nodes.size()*(nodes.size()-1))
 * @throws IllegalStateForMatrixException
 */
@Override
float density() throws IllegalStateForMatrixException {
    return (2 * (float) noEdges) / (nodes.size() * (nodes.size() - 1));
}

/**
 * Print out the adjacency matrix
 */
void print() {
    System.out.println(adjM);
}

}

【问题讨论】:

  • 您正在捕获异常,然后它们才能退出您的方法。或者你的实际问题是什么?
  • 欢迎来到 SO。一些建议,阅读How to Ask,发布minimal reproducible example,并解释“有问题”是什么意思。谢谢
  • 你的问题是什么?什么不按你想要的方式工作?
  • 如何正确抛出和捕获 IllegalStateForMatrix。我应该在哪里正确捕获异常?

标签: java arrays arraylist data-structures computer-science


【解决方案1】:

如何正确抛出和捕获 IllegalStateForMatrix。在哪里 我会正确捕获异常吗? ——

此处IllegalStateForMatrixException 表示对对象调用了一个操作,而该对象未处于接受此操作所需的先决条件的状态。

你想得到一些边但你没有矩阵? 这没有任何意义。

这是一个重要的问题,所以你必须引发异常直到引发异常的方法的调用者出现

除了这些方法之外,还声明了 throwing IllegalStateForMatrixException.
因此,如果检查了异常(不是 RuntimeException 的子项),则客户端必须处理它。

在您的代码中,有两种方法引发异常。
在这里你做的很好:

@Override
int getNumberOfEdges() throws IllegalStateForMatrixException {
    if (nodes.size() <= 0)
        throw new IllegalStateForMatrixException("Error");
    return noEdges;
}

您将异常抛出给必须处理它的客户端。

那里:

void addEdge(String fromNode, String toNode, int weight)
        throws ElementNotFoundException, IllegalStateForMatrixException {        
   try {
        if ( b == false)
           throw new IllegalStateForMatrixException("Exception");
        }
       ...
      }
    catch (IllegalStateForMatrixException e) {
       System.out.println("Exception found");
    }
       ...
}

当您在方法中提升异常时,您不允许将异常传播给调用者,但您也会捕获它。
与第一种情况一样,您不需要 try/catch 语句。

【讨论】:

  • 我是否也可以摆脱 ElementNotFoundException 的 try catch 呢?把它们扔掉就行了……顺便说一句,谢谢你的帮助。
  • 不客气 :) 这与 IllegalStateForMatrixException 相同。如果您在引发它的同一个地方捕获它,那么显式抛出 ElementNotFoundException 是什么意思?
猜你喜欢
  • 1970-01-01
  • 2013-05-24
  • 2013-01-16
  • 1970-01-01
  • 1970-01-01
  • 2011-01-22
  • 1970-01-01
  • 2011-03-28
  • 2016-06-02
相关资源
最近更新 更多