printStackTrace output to a String

Below example program shows how to convert output of printStackTrace to a String. As known, normal usage of printStackTrace directly outputs to console. But some times it would be required to collect stack trace into a String, mostly for logging purpose.


Here overloaded method printStackTrace(PrintWriter pw) is used.

import java.io.StringWriter;
import java.io.PrintWriter;

class Xyz{
	public void met1()
	{
		int j = 43,k=0;
		try
		{
		System.out.println("stmt 1");
		int i = j/k;
		System.out.println("stmt 2");
		}
		catch(Exception et)
		{
		//Below lines shows how to convert printStack Trace
		//output into a String
		StringWriter ets = new StringWriter();
		et.printStackTrace(new PrintWriter(ets));
		String str = ets.toString();
		//Now, required stack trace is in str

		System.out.println("Stacktrace as string: "+str);
		}
	}
}

public class Abc {
	public static void main(String args[])
	{
		System.out.println("in main");
		Xyz ox =new Xyz();
		ox.met1();
		System.out.println("exiting main");
	}
}