Kotlin Program to Convert a Stack Trace to a String

Example: Convert stack trace to a string

import java.io.PrintWriter
import java.io.StringWriter

fun main(args: Array<String>) {

    try {
        val division = 0 / 0
    } catch (e: ArithmeticException) {
        val sw = StringWriter()
        e.printStackTrace(PrintWriter(sw))
        val exceptionAsString = sw.toString()
        println(exceptionAsString)
    }

}

When you run the program, the output will be something similar:

java.lang.ArithmeticException: / by zero
	at StacktraceKt.main(stacktrace.kt:7)

In the above program, we've forced our program to throw ArithmeticException by dividing 0 by 0.

In 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.

Here's the equivalent Java code: Java program to convert a stack trace to a string.

Did you find this article helpful?