打印異常的堆棧信息
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
public class Test {
/**
* 獲取Exception的堆棧新息。用于顯示出錯(cuò)來源時(shí)使用。
* @param e
* Exception對(duì)象
* @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);
}
}
}
posted on 2008-07-04 09:38 李贊紅 閱讀(4438) 評(píng)論(5) 編輯 收藏