Posted By

maxkar on 10/31/08


Tagged

javastacktraceexception


Versions (?)

Stack trace as String


 / Published in: Java
 

URL: http://www.javapractices.com/topic/TopicAction.do?Id=78

  1. import java.io.*;
  2.  
  3. /**
  4. * Simple utilities to return the stack trace of an
  5. * exception as a String.
  6. */
  7. public final class StackTraceUtil {
  8.  
  9. public static String getStackTrace(Throwable aThrowable) {
  10. final Writer result = new StringWriter();
  11. final PrintWriter printWriter = new PrintWriter(result);
  12. aThrowable.printStackTrace(printWriter);
  13. return result.toString();
  14. }
  15.  
  16. /**
  17.   * Defines a custom format for the stack trace as String.
  18.   */
  19. public static String getCustomStackTrace(Throwable aThrowable) {
  20. //add the class name and any message passed to constructor
  21. final StringBuilder result = new StringBuilder( "BOO-BOO: " );
  22. result.append(aThrowable.toString());
  23. final String NEW_LINE = System.getProperty("line.separator");
  24. result.append(NEW_LINE);
  25.  
  26. //add each element of the stack trace
  27. for (StackTraceElement element : aThrowable.getStackTrace() ){
  28. result.append( element );
  29. result.append( NEW_LINE );
  30. }
  31. return result.toString();
  32. }
  33.  
  34. /** Demonstrate output. */
  35. public static void main (String... aArguments){
  36. final Throwable throwable = new IllegalArgumentException("Blah");
  37. System.out.println( getStackTrace(throwable) );
  38. System.out.println( getCustomStackTrace(throwable) );
  39. }
  40. }

Report this snippet  

You need to login to post a comment.