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");
	}
}

Example of PrintWriter

package fileionavigationexample;
import java.io.*;
public class PrintWriterExample {
public static void main(String[] args){
File file = new File(“C:\Users\KUNDAN\Documents\AdvanceJavaNotes.txt”);
try{
FileWriter fw = new FileWriter(file);
PrintWriter pw = new PrintWriter(fw);
pw.println(“Advance Java Is also Termed As Enterprise Edition ie. J2EE.”);
pw.println(“It includes Folowing Topics.”);
pw.println(“1) JDBC:Java Database Conectivity.”);
pw.println(“2) Servelet”);
pw.println(“3) JSP”);
pw.println(“4) Hibernate”);
pw.println(“5) Spring”);
pw.println(“6) Struts”);

pw.close();
fw.close();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String f = br.readLine();
while((f = br.readLine()) != null){
System.out.println(f);
}
br.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
}