Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to print stack trace on demand?

I am looking for a way to get a stack trace when I am at a certain breakpoint. Is this possible? Ideally without having to crash the application and modifying the code. I tried playing with the Android debugger but couldn't find anything very helpful.

The reason is that sometimes I am not certain how the application arrived at a point in code, so I am open to other suggestions that would help me trace the method calls.

like image 795
JohnEye Avatar asked Aug 09 '12 13:08

JohnEye


People also ask

How do I print a stack trace file?

Use a proper logging API like Log4J, configure a file appender and call one of the overloaded logging methods that accepts a Throwable. printStracktrace also accepts a printstream as parameter. thus you can create a printstream to a file and voila. printStracktrace also accepts a printstream as parameter.

How do I print a string stack trace?

Example: Convert stack trace to a stringIn the catch block, we use StringWriter and PrintWriter to print any given output to a string. We then print the stack trace using printStackTrace() method of the exception and write it in the writer. Then, we simply convert it to string using toString() method.

How can I print stack trace without exception?

Just use new Throwable(). printStackTrace() method and it will print complete stack trace from where a method is called, into the console. Main difference between using dumpStack() and printStackTrace() is first entry in Stack, In case of dumpStack() first entry is always java.

Should we print stack trace?

printStackTrace() is very useful in diagnosing exceptions. For example, if one out of five methods in your code cause an exception, printStackTrace() will pinpoint the exact line in which the method raised the exception.


3 Answers

This can be done in Java:

new Throwable().printStackTrace();

In Eclipse, if you create an "expression" with that code in the Expressions view of Debug perspective, it will print current stack trace (i.e. the stacktrace of the breakpoint your code stopped on) in the Console view.

like image 99
npe Avatar answered Nov 17 '22 11:11

npe


Log.e("AppName", "Debug exception", new Exception());
like image 31
Jonathon Faust Avatar answered Nov 17 '22 12:11

Jonathon Faust


The easiest way is to throw an exception, immediately catch it and use printStackTrace().

You could also try Thread.currentThread().getStackTrace() which gives you a StackTraceElement[] in case you want to to anything else besides having the textual representation that printStackTrace() does.

like image 2
f1sh Avatar answered Nov 17 '22 13:11

f1sh