Quantcast
Channel: Developer Feed - Snippet
Viewing all articles
Browse latest Browse all 178

Get StackTrace as String

$
0
0

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
*/


publicclass PrintStackTrace {

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

publicstaticfinalvoid 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
*/

publicvoid exec() {
methodA();
}

/**
* Sample method
*/

publicvoid methodA() {
methodB();
}

/**
* Sample method
*/

publicvoid methodB() {

methodC();
}

publicvoid methodC() {
thrownew 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)


Viewing all articles
Browse latest Browse all 178

Trending Articles