How to Convert Stacktrace to String in Java


The example aims to convert Stacktrace to String in Java.

Source Code

package com.beginner.examples;
 
import java.io.PrintWriter;
import java.io.StringWriter;
 
public class StackTraceToString {
 
	
	public static void main(String[] args) {
		try {
			//this will throw Exception.
			String[] arr = {"111", "222"};
			arr[2] = "fff";
		} catch (Exception e) {
			String info = getErrorInfoFromException(e);
			System.out.println(info);
		}
	}
	
	public static String getErrorInfoFromException(Exception e) {
		try {
			/*
			 * To convert Stacktrace to String in Java, use 
			 * printStackTrace(PrintWrite pw) method of Throwable.
			 */
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw);
			e.printStackTrace(pw);
			return "rn" + sw.toString() + "rn";
		} catch (Exception e2) {
			return "bad getErrorInfoFromException";
		}
	}
}

Output:

java.lang.ArrayIndexOutOfBoundsException: 2
	at com.beginner.examples.StackTraceToString.main(StackTraceToString.java:14)

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments