打印异常的堆栈信息

打印异常的堆栈信息

package com.aptech.print;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
public class Test {
/**
     * 获取Exception的堆栈新息。用于显示出错来源时使用。
     * @param e
     *            Exception对象
     * @param length
     *            需要的信息长度,如果 <=0,表示全部信息
     * @return String 返回该Exception的堆栈新息
     * @author 李赞红
     */
public static String getErrorStack(Exception e, int length) {
  String error = null;
  if (e != null) {
   try {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(baos);
    e.printStackTrace(ps);
    error = baos.toString();
    if (length > 0) {
     if (length > error.length()) {
      length = error.length();
     }
     error = error.substring(0, length);
    }
    baos.close();
    ps.close();
   } catch (Exception e1) {
    error = e.toString();
   }
  }
  /*
   * try{ String str=new String(error.getBytes("ISO-8859-1"),"GBK");
   * return str; }catch(Exception e1) { e1.printStackTrace(); }
   */
  return error;
}

public static void main(String[] args) {
  try {
   Integer.parseInt("中华人民共和国");
  } catch (NumberFormatException e) {
   String s = Test.getErrorStack(e, 0);
   System.out.println("异常信息:" + s);
  }
  
}
}

你可能感兴趣的:(打印异常的堆栈信息)