這一個有點難以解釋,所以對於長問題的抱歉!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
謝謝!
或者你可以簡單地重新拋出異常之前。或者將先前例外的堆棧跟蹤傳送到新的例外。 – 2013-05-02 22:03:34