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.
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.
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.
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.
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.
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.
Log.e("AppName", "Debug exception", new Exception());
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With