Jump to Real's How-to Main page

Redirect printStackTrace() to a String

import java.io.*;

public class TestStack2String {
 public static void main(String s[]){
  try {
    // force an exception for demonstration purpose
    Class.forName("unknown").newInstance();
    // or this could be changed to:
    //    throw new Exception();

  }
  catch (Exception e) {
    System.out.println(stack2string(e));
  }
 }

 public static String stack2string(Exception e) {
  try {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    e.printStackTrace(pw);
    return "------\r\n" + sw.toString() + "------\r\n";
  }
  catch(Exception e2) {
    return "bad stack2string";
  }
 }
}

If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2005
[ home ]