Breaking News
Home / Java / Java Snippets / Get StackTrace as String

Get StackTrace as String

Java StackTrace

Its easy to print the stack trace using e.printStackTrace() where e is instance of an Exception/Throwable. This prints the trace to the Standard Error stream. But how about if you want to have the stacktrace stored in file or database or want to search as text.

This snippets shows how to get the stack trace as String.

 

package com.livrona.snippets.system;

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

/**
* This snippet shows how to get java stack traces for exceptions as a string.
*
* @author mvohra
*/


public class PrintStackTrace {

/**
* Main method
*
* @param args
* @throws Exception
*/

public static final void main(String args[]) throws Exception {

// create a sample exception
PrintStackTrace strace = new PrintStackTrace();

try {

// execute the logic
strace.exec();
} catch (Exception e) {

// get the trace and print
String stackTrace = strace.getStackTrace(e);
System.out.println(stackTrace);
}
}

/**
* Returns the stack trace as String
*
* @param t
* @return
*/

public String getStackTrace(Throwable t) {
String stackTrace = null;

try {
StringWriter sw = new StringWriter();

// print the stack trace using the
// print writer into the string writer
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);

// close the writers.
pw.close();
sw.close();

// get the stack trace
stackTrace = sw.getBuffer().toString();
} catch (Exception ex) {
}
return stackTrace;
}

/**
* Execution
*/

public void exec() {
methodA();
}

/**
* Sample method
*/

public void methodA() {
methodB();
}

/**
* Sample method
*/

public void methodB() {

methodC();
}

public void methodC() {
throw new RuntimeException("Exception : some thing wrong here!");
}

}
The output is as follows:

java.lang.RuntimeException: Exception : some thing wrong here!
at com.livrona.snippets.system.PrintStackTrace.methodC(PrintStackTrace.java:75)
at com.livrona.snippets.system.PrintStackTrace.methodB(PrintStackTrace.java:71)
at com.livrona.snippets.system.PrintStackTrace.methodA(PrintStackTrace.java:63)
at com.livrona.snippets.system.PrintStackTrace.exec(PrintStackTrace.java:56)
at com.livrona.snippets.system.PrintStackTrace.main(PrintStackTrace.java:25)

[pb_builder]

Check Also

How to progamatically get the Java version?

Snippet The key here is to use the system property java.version and get minor and …

Leave a Reply