Reputation: 20224
What's the easiest way to print a stacktrace from a debugging printout? Often during testing you would like to know the callstack leading up to the situation provoking a debug message.
Upvotes: 12
Views: 17171
Reputation: 4866
To simply print the current stack trace to stderr, you can call:
Thread.dumpStack();
which itself just calls:
new Exception("Stack trace").printStackTrace();
To output to stdout rather than stderr, pass System.out
to printStackTrace()
:
new Exception("Stack trace").printStackTrace(System.out);
Upvotes: 2
Reputation: 28810
If you're using log4j
Exception e = new Exception();
log.error("error here", e);
will print the stacktrace to your log.
Upvotes: 20
Reputation: 83597
Just because I needed it myself:
As inspired by answer How do I find the caller of a method using stacktrace or reflection? , you can retrieve the call stack using
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace()
Then you process and print/log whatever you are interested in. More work than using Thread.dumpStack()
, but more flexible.
Upvotes: 1
Reputation:
If you want to save the stack trace into a String you can do this;
String exception = "";
for (StackTraceElement element : e.getStackTrace())
exception += element.toString() + "\n";
Where e is, obviously, an exception.
Besides, it sounds very weird to autogenerate an own Exception just to find get a stack trace for a debug. Get Eclipse and use it's debug mode, it's really awesome.
Upvotes: 6
Reputation: 182782
As well as what @jjnguy said, if you don't have an exception, you can also call Thread.getStackTrace().
Upvotes: 3
Reputation: 20224
Just creating an arbitrary exception does the trick for me:
System.out.println("Oops, the bad thing happened");
new IllegalStateException().printStackTrace();
Upvotes: 4
Reputation: 138874
You should be catching the exception in a try-catch block.
e.getStackTrace();
That returns StackTraceElement[] that you can then interpret.
Also:
e.printStackTrace()
will...print the stacktrace.
Upvotes: 2