java - What is the correct way to compare two throwables? -
i using junit rule re-run failed tests. requirement is, if re-run fails, determine whether failed same reason.
to i've adapted code this answer keep record of failures , compare them. however, comparison (.equals) evaluates false despite them failing same reason. best way go this?
private statement statement(final statement base, final description description) { return new statement() { @override public void evaluate() throws throwable { (int = 0; < retrycount; i++) { try { base.evaluate(); return; } catch (throwable t) { system.err.println(description.getdisplayname() + ": run " + (i + 1) + " failed"); // compare error 1 before it. if (errors.size() > 0) { if (t.equals(errors.get(errors.size() - 1))) { system.out.println("the error same previous one!"); } else { system.out.println("the error different previous one."); } } errors.add(t); } } system.err.println(description.getdisplayname() + ": giving after " + retrycount + " failures"); // throw recent error. throw errors.get(errors.size() - 1); } }; }
equality throwable
defined "the same throwable
". (it compares references.)
"same reason" need think , define application.
one way define "the same type , loosely same throw
statement":
static boolean sametypeandline(throwable t1, throwable t2) { if (t1.getclass() == t2.getclass()) { stacktraceelement[] trace1 = t1.getstacktrace(); stacktraceelement[] trace2 = t2.getstacktrace(); return trace1[0].equals(trace2[0]); } else { return false; } }
but still has ambiguity:
if (bad1 || bad2) { // same throw site, different conditions throw new exception(...); }
// throws nullpointerexeption // (was foo or result of bar() null?) object baz = foo.bar().baz();
so, best thing can define reasons exceptions:
class myexception { final reason reason; myexception(reason reason) { this.reason = reason; } // or class, or whatever need enum reason {a, b, c} }
and check against those. additionally, use coding style prevents ambiguities.
Comments
Post a Comment