How to convert a stack trace to string in Kotlin

How to convert a stack trace to string in Kotlin:

Stack Trace is useful to find the root cause of an exception. Sometimes we need to convert a stack trace to a string. For example, if we want to send the stack trace to our server, we need to convert it to a string. Normally, we don’t do that. Crashlytics like *Firebase crashlytics *handles that automatically.

But, even during development time, you can convert a stack trace to string to make it more readable.

In this post, we will learn how to convert a stack trace to string in Kotlin with an example.

Stack trace to string in Kotlin:

To convert a stack trace to string, we need to use the StringWriter and PrintWriter classes. Exceptions have one method called printStackTrace where we can pass one PrintWriter object. This will send the exception to the PrintWriter. If we create the PrintWriter using a StringWriter, we can get the string value of the stack trace by using the toString() method.

Below is the complete program:

package com.company

import java.io.PrintWriter
import java.io.StringWriter
import java.lang.Integer.parseInt

fun main() {
    try {
        parseInt(null)
    } catch (e: NumberFormatException) {
        val stringWriter = StringWriter()
        val printWriter = PrintWriter(stringWriter)

        e.printStackTrace(printWriter)

        print(stringWriter.toString())
    }
}

Here,

  • This program will throw NumberFormatException since we are using parseInt on a null value.
  • The printStackTrace method is called on this exception and PrintWriter object is passed to it.

It will print the output as like below:

Kotlin convert stacktrace to string

You might also like: