StackTraceElement用于跟踪异常

时间:2013-05-02 21:48:30

标签: java exception-handling

这个问题有点难以解释,很抱歉这个问题很长!

我有方法indexOf(String node),它查找字符串数组并返回索引位置,如果它无法在数组中找到节点字符串,则抛出异常。

此方法在addEdge(String node1,String node2)中用于调用addEdge(int index1,int index2)。

protected String[] nodes;
protected boolean[][] adjacencyMatrix;

protected int indexOf(String node) throws GraphException {
    for (int i = 0; i < nodes.length; i++) {
        if (node.equals(nodes[i])) {
            return i;
        }
    }
    System.out.println("Exception in indexOf(String node)");
    throw new GraphException();
}

public void addEdge(int index1, int index2) throws GraphException {
    if ((index1 != index2) && (index1 < this.nodes.length) && (index2 < this.nodes.length)) {
        this.adjacencyMatrix[index1][index2] = true;
        this.adjacencyMatrix[index2][index1] = true;
    } else {
        System.out.println("Exception in addEdge(int index1, int index2)");
        throw new GraphException();
    }
}

public void addEdge(String node1, String node2) throws GraphException {
    try {
        this.addEdge(this.indexOf(node1), this.indexOf(node2));

    } catch (GraphException e) {
        System.out.println("Exception in addEdge(String node1, String node2)");
        throw new GraphException();
    }
}

出于测试目的,我使用myArray = {&#34; foo&#34;,&#34; foo2&#34;,&#34; bar&#34;}实现了一个数组。现在,当我尝试引发异常时,例如:

try {
        addEdge("foo", "foobar");

    } catch (GraphException e) {
        for (StackTraceElement st : e.getStackTrace()) {
            System.out.println("Method: " + st.getMethodName() + " Line: " + st.getLineNumber());
        }
    }

控制台输出是:

Exception in indexOf(String node)
Exception in addEdge(String node1, String node2)
Method: addEdge Line: 169
Method: main Line: 221

好的,问题在于:

显然,必须首次在indexOf(String节点)中抛出异常,因为没有匹配的&#34; foobar&#34;节点数组中的字符串。

解释了indexOf(String node)中的第一个.println:异常。

那么,是否有一个原因是Stack错过了抛出异常的第一个位置?

我会从堆栈中得到这样的东西:

Method: indexOf Line: 58
Method: addEdge Line: 169
Method: main Line: 221

谢谢!

1 个答案:

答案 0 :(得分:1)

你的异常被addEdge(string, string)捕获并重新抛出,这就是堆栈跟踪开始的地方。

如果要保留实际的启动堆栈跟踪,则必须修改GraphException,以便它也可以包含先前的异常:

throw new GraphException (e);