java - StackTraceElement for tracking an exception -
this 1 little bit tough explain, sorry long question!
i have method indexof(string node) looks in string-array , returns index-position or throws exception if can't find node-string in array.
this method used in addedge(string node1, string node2) call addedge(int index1, int index2).
protected string[] nodes; protected boolean[][] adjacencymatrix; protected int indexof(string node) throws graphexception { (int = 0; < 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(); } }
for testing purposes, have implemented array myarray = {"foo", "foo2", "bar"}. now, when try provoke exception, like:
try { addedge("foo", "foobar"); } catch (graphexception e) { (stacktraceelement st : e.getstacktrace()) { system.out.println("method: " + st.getmethodname() + " line: " + st.getlinenumber()); } }
the console-output is:
exception in indexof(string node) exception in addedge(string node1, string node2) method: addedge line: 169 method: main line: 221
ok, here's question:
apperently, exception must have been thrown in indexof(string node) first time, since there no matching "foobar" string in nodes-array.
that's explaining first .println: exception in indexof(string node).
so, there reason stack missing out first position exception gets thrown?
i have expected stack:
method: indexof line: 58 method: addedge line: 169 method: main line: 221
thank you!
your exception being caught in addedge(string, string)
, rethrown, that's stacktrace starts.
if want preserve actual initiating stacktrace, you'll have modify graphexception
can carries previous exception:
throw new graphexception (e);
Comments
Post a Comment