现在的位置: 首页 > 综合 > 正文

如何记录异常的 堆栈信息

2013年12月06日 ⁄ 综合 ⁄ 共 598字 ⁄ 字号 评论关闭


一 利用log4j:

在catch加入:

logger.error("oops, got an exception: ", e);

二 自己自定义类:

public class StackTraceToString {

/**
* @param args
*/
public static void main(String[] args) {

   try{
    System.out.println(args[0]);
   }catch(Exception e){
    System.out.println(e.getMessage());
    System.out.println("xxxxxxxxxxxxx");
    System.out.println(getExceptionTrace(e));
   }
}

public static String getExceptionTrace(Throwable e){
   if(e!=null){
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    e.printStackTrace(pw);
    pw.flush();
    pw.close();
    return sw.toString();
   }else{
    String result = "No Exception";
    return result;
   }
}
}

【上篇】
【下篇】

抱歉!评论已关闭.