English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin program converts stack trace to string

Kotlin Complete Examples

In this program, you will learn how to convert a stack trace to a string in Kotlin.

Example: Convert stack trace to 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 similar to the following content:

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

In the above program, we force the program to throw an ArithmeticException by dividing 0 by 0.

In the catch block, we use StringWriter and PrintWriter to print any given output to a string. Then, we use the exception's method printStackTrace() to print the stack trace and write it to the writer.

Then, we just use the toString() method to convert it to a string.

This is the equivalent Java code:Java Program Converts Stack Trace to String.

Kotlin Complete Examples