0

I have a question that I want to know "How to print CallStack in kotlin?". Thanks

Ricky Mo
  • 6,285
  • 1
  • 14
  • 30
刘路扬
  • 19
  • 3
  • 1
    You can refer to the java method [How can I get the current stack trace in Java?](https://stackoverflow.com/questions/1069066/how-can-i-get-the-current-stack-trace-in-java), simply translate it into kotlin – Ricky Mo Jun 06 '23 at 08:47
  • 1
    `Exception().printStackTrace()` – Tenfour04 Jun 06 '23 at 12:11
  • best practice: Lod.d(TAG, "Stack: ${Log.getStackTraceString(Throwable())}") – 刘路扬 Jun 21 '23 at 02:50

2 Answers2

0

To print the CallStack in Kotlin, you can use the Throwable.getStackTrace() method and print the stack trace using the println() function. Here is an example:

fun main() {
 try {
    divide(10, 0)
 } catch (e: Exception) {
    e.printStackTrace()
 }
}

fun divide(a: Int, b: Int): Int {
  return a / b
}

In this example, we are calling the divide() function with two arguments: 10 and 0, which will lead to an ArithmeticException. So we are catching the exception and printing the stack trace using the e.printStackTrace() method. The output will look something like this:

java.lang.ArithmeticException: / by zero
   at MainKt.divide(Main.kt:10)
   at MainKt.main(Main.kt:4)

This shows the call stack for the exception, starting with the exception itself and going back to the original method call that caused the exception.

DASSDED
  • 26
  • 2
0

Lod.d(TAG, "Stack: ${Log.getStackTraceString(Throwable())}")

刘路扬
  • 19
  • 3