ExceptionUtils.getFullStackTrace 旧城等待, 2021-09-14 01:44 145阅读 0赞 **\[java\]** [view plain][] [copy][view plain] 1. //打印全部异常堆栈 2. **public** **class** ExceptionUtils \{ 3. **public** **static** **void** main(String\[\] args) \{ 4. **try** \{ 5. **int** a=1/0; 6. \} **catch** (Exception e) \{ 7. e.printStackTrace(); 8. String fullStackTrace = org.apache.commons.lang.exception.ExceptionUtils.getFullStackTrace(e); 9. System.out.println(fullStackTrace); 10. 11. \} 12. \} 13. \} **\[java\]** [view plain][] [copy][view plain] 1. /\*\* 2. \* <p>A way to get the entire nested stack-trace of an throwable.</p> 3. \* 4. \* <p>The result of this method is highly dependent on the JDK version 5. \* and whether the exceptions override printStackTrace or not.</p> 6. \* 7. \* @param throwable the <code>Throwable</code> to be examined 8. \* @return the nested stack trace, with the root cause first 9. \* @since 2.0 10. \*/ 11. **public** **static** String getFullStackTrace(Throwable throwable) \{ 12. StringWriter sw = **new** StringWriter(); 13. PrintWriter pw = **new** PrintWriter(sw, **true**); 14. Throwable\[\] ts = getThrowables(throwable); 15. **for** (**int** i = 0; i < ts.length; i++) \{ 16. ts\[i\].printStackTrace(pw); 17. **if** (isNestedThrowable(ts\[i\])) \{ 18. **break**; 19. \} 20. \} 21. **return** sw.getBuffer().toString(); 22. \} 另一种方式: **\[java\]** [view plain][] [copy][view plain] 1. **public** **static** String exception2String(Exception ex)\{ 2. String exceptionMessage = ""; 3. **if** (ex != **null**) \{ 4. StringWriter sw = **new** StringWriter(); 5. PrintWriter pw = **new** PrintWriter(sw); 6. **try** \{ 7. ex.printStackTrace(pw); 8. exceptionMessage = sw.toString(); 9. \} **finally** \{ 10. **try** \{ 11. sw.close(); 12. pw.close(); 13. \} **catch** (Exception e) \{ 14. \} 15. \} 16. \} 17. **return** exceptionMessage; 18. \} 19. [view plain]: http://blog.csdn.net/lw4135/article/details/52208786#
还没有评论,来说两句吧...