Friday, April 13, 2012

Get complete exception trace as a String

In some cases we want to write the complete exception stackTrace to a file, in that case use below method which will take Throwable object as a input and returns complete stackTrace as a String.

By using below method you can get complete exception stack trace as a String.

public static String stackTraceToString(Throwable e) 
{
  String retValue = null;
  StringWriter sw = null;
  PrintWriter pw = null;
  try {
                  sw = new StringWriter();
                  pw = new PrintWriter(sw);
                  e.printStackTrace(pw);
                retValue = sw.toString();
  } 
               finally 
               {
           try {
                       if(pw != null) { pw.close();}
                       if(sw != null) { sw.close();}
               } 
                       catch (IOException ignore) {
    ignore.printStackTrace();
             }
      }
 return retValue+" \n ";
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.