如何在 Kotlin 中打印调用堆栈?

huangapple go评论61阅读模式
英文:

How to print CallStack in kotlin?

问题

我有一个问题,我想知道如何在Kotlin中打印CallStack。谢谢。

英文:

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

答案1

得分: 0

要在Kotlin中打印CallStack,可以使用Throwable.getStackTrace()方法并使用println()函数打印堆栈跟踪。这是一个例子:

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

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

在这个例子中,我们调用divide()函数并传入两个参数:10和0,这将导致ArithmeticException。因此,我们捕获异常并使用e.printStackTrace()方法打印堆栈跟踪。输出将类似于以下内容:

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

这显示了异常的调用堆栈,从异常本身开始,回溯到导致异常的原始方法调用。

英文:

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.

答案2

得分: 0

"Lod.d(TAG, "Stack: ${Log.getStackTraceString(Throwable())}")" 可以翻译为 "Lod.d(TAG, "堆栈: ${Log.getStackTraceString(Throwable())}")"。

英文:

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

huangapple
  • 本文由 发表于 2023年6月6日 16:40:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76412862.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定