Tuesday, May 10, 2005

Java Sample code to write exception stack trace in to a file.

My previous code is too big. So I will add small code today.
Normally in the try catch block, if we have exception object, we will print exception object with printStatckTace, getErrorMessage etc. But I faced a situation in which, I need to log all the exception trace back stack in to a text file. Later admin want to view this log file for all tracebacks.
Just think how to write exception trace in to a txt file.
Here is the code block for the above problem.

StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
StringBuffer error = sw.getBuffer();
String exceptionString = error. toString()
Note: StringWriter, PrintWriter classes comes from io package.

No comments: