English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn how to convert stack trace to string in Java.
import java.io.PrintWriter; import java.io.StringWriter; public class PrintStackTrace { public static void main(String[] args) { try { int division = 0 / 0; } catch (ArithmeticException e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); String exceptionAsString = sw.toString(); System.out.println(exceptionAsString); } } }
When you run the program, the output will be similar to the following content:
java.lang.ArithmeticException: / by zero at PrintStackTrace.main(PrintStackTrace.java:9)
In the above program, we force the program to throw an ArithmeticException by dividing 0 by 0
In the catch block, we use StringWriter and PrintWriter to print any given output as a string. Then we use the exception's printStackTrace() method to print the stack trace and write it to the writer
Then, we just need to use the toString() method to convert it to a string.