Refactored to obtain the exception stack information-printStackTrace

Source: Internet
Author: User

Refactored to obtain the exception stack information-printStackTrace

MyStackTrace:

/**  *  * @author wumingkun * @version 1.0.0 * @Description */package com.demo.stacktrace;import java.io.PrintStream;/** * @author wumingkun *  */public class MyStackTrace {public static String getStackTrace(Throwable errors) {StringBuffer result = new StringBuffer();result.append(errors);StackTraceElement[] trace = errors.getStackTrace();for (int i = 0; i < trace.length; i++)result.append("\n\tat " + trace[i]); Throwable ourCause = errors.getCause();         if (ourCause != null)             result.append(getStackTraceAsCause(ourCause, trace));return result.toString();}private static String  getStackTraceAsCause(Throwable ourCause,StackTraceElement[] causedTrace) {StringBuffer result=new StringBuffer();StackTraceElement[] trace = ourCause.getStackTrace();int m = trace.length - 1, n = causedTrace.length - 1;while (m >= 0 && n >= 0 && trace[m].equals(causedTrace[n])) {m--;n--;}int framesInCommon = trace.length - 1 - m;result.append("\nCaused by: " + ourCause);for (int i = 0; i <= m; i++)result.append("\n\tat " + trace[i]);if (framesInCommon != 0)result.append("\n\t... " + framesInCommon + " more");Throwable tempCause = ourCause.getCause();if (tempCause != null)result.append(getStackTraceAsCause(tempCause, trace));return result.toString();}}


StackTraceTest:

/***** @ Author wumingkun * @ version 1.0.0 * @ Description */package com. demo. stacktrace;/*** @ author wumingkun ***/public class StackTraceTest {/*** @ param args */public static void main (String [] args) {try {m1 ();} catch (Exception e) {System. out. println (MyStackTrace. getStackTrace (e); // returns the exception stack information string}/*****/private static void m1 () {StringBuffer sb = null; try {sb. append ("aa");} catch (Exception e) {throw new RuntimeException (e );}}}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.