Thilo-Alexander Ginkel
Thilo-Alexander Ginkel

Reputation: 6958

Determining Current Call Stack (For Diagnostic Purposes)

For diagnostic purposes I sometimes need to store the call stack that lead to a given state transition (such as granting a lock, committing a transaction, etc.) so that when something goes wrong later I can find out who originally triggered the state transition.

Currently, the only way I am aware of to retrieve the call stack looks like the following code snippet, which I consider terribly ugly:

StackTraceElement[] cause;
try {
  throw new Exception();
} catch (Exception e) {
  cause = e.getStackTrace();
}

Does somebody know of a better way to accomplish this?

Upvotes: 57

Views: 26421

Answers (4)

nyx
nyx

Reputation: 489

There's a new option since JDK 9: StackWalker

It isn't as expensive as Thread.currentThread().getStackTrace().

see also How Expensive is Thread.getStackTrace()?

Upvotes: 3

Edward Anderson
Edward Anderson

Reputation: 13916

If you want it as a String and use Apache Commons:

org.apache.commons.lang.exception.ExceptionUtils.getFullStackTrace(new Throwable())

Upvotes: 3

bruno conde
bruno conde

Reputation: 48265

I think you can get the same thing with:

StackTraceElement[] cause = Thread.currentThread().getStackTrace();

Upvotes: 106

Michael Myers
Michael Myers

Reputation: 191855

Well, you can improve it slightly by not actually throwing the exception.

Exception ex = new Exception();
ex.fillInStackTrace();
StackTraceElement[] cause = ex.getStackTrace();

Actually, I just checked: the constructor calls fillInStackTrace() already. So you can simplify it to:

StackTraceElement[] cause = new Exception().getStackTrace();

This is actually what Thread.getStackTrace() does if it's called on the current thread, so you might prefer using it instead.

Upvotes: 17

Related Questions