Java print stack trace to string | How to Convert Program example

Using Core Java API to print the stack trace to strings provides an easy and efficient way to convert stack trace to string using StringWriter and PrintWriter.

A printStackTrace() method is used for get information about exception. You don’t need any special method to convert a print stack trace to a string. In the try-catch-finally exceptions block, we did it in a simple way.

Example: Convert and Print stack trace to a string

This program will throw ArithmeticException by dividing 0 by 0.

Complete code

In code, Calling writer.toString() will provide stack trace in String format.

In the catch block, 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.


Java print stack trace to string

We don’t think you need to convert a Stack trace because you can use simple printStackTrace() method or print direct exception as below code:-


Java printStackTrace method

Do comment if you have any doubts and suggestions on this tutorial.

Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1
Java version 11
All Java printStackTrace() methdo codes are in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.