Kotlin Program to Convert a Stack Trace to a String

Kotlin Program to Convert a Stack Trace to a String. In the catch block, we use StringWriter and PrintWriter to print any given output to a string. We then print the stack trace using the printStackTrace() method of the exception and write it in the writer.

Kotlin Program to Convert a Stack Trace to a String

Source Code

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)
    }

}

Output