Kotlin Program to Convert a Stack Trace to a String

1. Introduction


In this article, You'll learn how to convert kotlin stack trace to a String programmatically. 

This is part of the Kotlin Program Series


Kotlin Program to Convert a Stack Trace to a String


2. Example To Convert Stack Trace To String


[package com.javaprogramto.kotlin.exceptions.stacktrace
import java.io.PrintWriter
import java.io.StringWriter
fun main(args: Array<String>) {
try {
var number = 100;
var division = number / 0;
} catch (e: ArithmeticException){
val stringWriter = StringWriter()
e.printStackTrace(PrintWriter(stringWriter))
val exceptionAsString = stringWriter.toString()
println(exceptionAsString)
}
}]

Output:

java.lang.ArithmeticException: / by zero
at com.javaprogramto.kotlin.exceptions.stacktrace.StackTraceToStringExampleKt.main(StackTraceToStringExample.kt:12)

In the above example, we tried to produce the ArtithmeticException by doing number / 0. If any number is divided by '0' then it will cause a runtime exception. Because it is going to produce invalid and break the code.

First, 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.

Finally, Call toString() method to convert into String on StringWriter.

3. Conclusion

In conclusion, You have seen how to wrap the exception into a String.

All the code is shown in this article is over GitHub.

You can download the project directly and can run in your local without any errors.

[View on GitHub ##eye##]

[Download ##file-download##]


If you have any queries please post in the comment section.

0 Comments