将异常(getStackTrace)转化成String
方法一:
private static String getStackMsg(Exception e) { StringBuffer sb = new StringBuffer(); StackTraceElement[] stackArray = e.getStackTrace(); for (int i = 0; i < stackArray.length; i++) { StackTraceElement element = stackArray[i]; sb.append(element.toString() + "\n"); } return sb.toString(); } private static String getStackMsg(Throwable e) { StringBuffer sb = new StringBuffer(); StackTraceElement[] stackArray = e.getStackTrace(); for (int i = 0; i < stackArray.length; i++) { StackTraceElement element = stackArray[i]; sb.append(element.toString() + "\n"); } return sb.toString(); }
方法二:
package com.test1; import java.io.PrintWriter; import java.io.StringWriter; public class T010 { /** * @param args */ public static void main(String[] args) { try { String[] arr = {"111", "222"}; arr[2] = "fff"; } catch (Exception e) { String info = getErrorInfoFromException(e); System.out.println(info); } } public static String getErrorInfoFromException(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 getErrorInfoFromException"; } } }
posted on 2015-06-15 09:50 xunianchong 阅读(2573) 评论(0) 编辑 收藏 举报