Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
Python online compiler
JavaScript online compiler
SQL online compiler
Java online compiler
HTML online compiler
C online compiler
C++ online compiler
C# online compiler
PHP online compiler
Swift online compiler
Kotlin online compiler
TypeScript online compiler
Go online compiler
Rust online compiler
Scala online compiler
Dart online compiler
R online compiler
Ruby online compiler
Kotlin Program to Convert a Stack Trace to a String
In this program, you'll learn to convert a stack trace to a string in Kotlin.
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?