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.
StringWriter writer = new StringWriter(); PrintWriter printWriter= new PrintWriter(writer); exception.printStackTrace(printWriter);
Complete code
In code, Calling writer.toString() will provide stack trace in String format.
In the catch block, StringWriter and PrintWriter 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.
import java.io.PrintWriter; import java.io.StringWriter; public class TryCatchBlock { public static void main(String[] args) { try { int a[] = new int[10]; a[11] = 30 / 0; } catch (Exception e) { StringWriter writer = new StringWriter(); PrintWriter printWriter= new PrintWriter(writer); e.printStackTrace(printWriter); System.out.println("Exception in String is :: " + writer.toString()); } System.out.println("Remain codes"); } }
Output:
We don’t think you need to convert a Stack trace because you can use the simple printStackTrace() method or print direct exception as below code:-
public class TryCatchBlock { public static void main(String[] args) { try { int a[] = new int[10]; a[11] = 30 / 0; } catch (Exception e) { // 1st Way e.printStackTrace(); // 2nd way System.out.println(e); } System.out.println("Remain codes"); } }
Output:
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.