2013-05-02 82 views
0

这一个有点难以解释,所以对于长问题的抱歉!StackTraceElement用于跟踪异常

我有方法indexOf(String node),它查找一个字符串数组并返回index-position,或者在数组中找不到节点字符串时抛出一个Exception。

此方法用于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的= { “foo” 的, “foo2的”, “杆”}的阵列。现在,当我尝试一些挑起异常,如:

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 

好吧,这里的问题是:

Apperently,除了必须由于在节点数组中没有匹配的“foobar”字符串,因此第一次在indexOf(String节点)中被抛出。

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

那么,是否有一个原因,堆栈错过了第一个地方的异常被抛出?

我本来期望像这样从栈:

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

谢谢!

回答

1

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

如果您想保留实际的引发堆栈跟踪,你就必须修改GraphException如此,它也可以携带以前的例外:

throw new GraphException (e); 
+1

或者你可以简单地重新抛出异常之前。或者将先前例外的堆栈跟踪传送到新的例外。 – 2013-05-02 22:03:34