package com.iden.util; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; public class HandleException { /** * Return StackTrace information * @param throwObj * @return */ private static String getStackTrace(Throwable throwObj) { final Writer result = new StringWriter(); final PrintWriter printWriter = new PrintWriter(result); throwObj.printStackTrace(printWriter); return result.toString(); } /** * Return custom StackTrace information * @param throwObj * @return */ private static String getCuctomStackTrace(Throwable throwObj) { final StringBuilder result = new StringBuilder("HandleException.getCuctomStackTrace(): "); result.append(throwObj.toString()); final String NEW_LINE = System.getProperty("line.separator"); result.append(NEW_LINE); for (StackTraceElement element : throwObj.getStackTrace()) { result.append(element); result.append(NEW_LINE); } return result.toString(); } public static void main(String[] args){ try{ throw new NullPointerException("Iden test"); //throw new AlreadyBoundException("Iden test"); }catch(Exception e){ if(e instanceof java.lang.NullPointerException){ System.out.println(getStackTrace(e)); System.out.println(getCuctomStackTrace(e)); } } } }
11/10/2009
Java中像 printStackTrace() 拋出 Stack String
有時侯需要將stack中的例外訊息拋出來給使用者查詢或寫成log,這時侯就需要下面的程式了。
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言