- Redirect printStackTrace() to a String

类别:Java 点击:0 评论:0 推荐:

 import java.io.*;

public class TestStack2String {
  public static void main(String s[]){
   try {
     // force an exception for demonstration purpose
     Class.forName("unknown").newInstance();
     }
   catch (Exception e) {
     System.out.println(stack2string(e));
     }
   }

  static public 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";
     }
   }
}

本文地址:http://com.8s8s.com/it/it18909.htm