The Exception class has a printStackTrace () method, which is capable of outputting stack information from an abnormal method, and the default output location is System.err. However, sometimes we want to output the stack information elsewhere outside of System.err, such as outputting the stack information to email when an exception occurs, or is displayed in a dialog. The printstackTrace () method has several different types: · PrintStackTrace (), output to standard error flow. · PrintStractRace (PrintStream PS) output to PrintStream named PS. · PrintStackTrace (PrintWriter PW) output to PrintWriter named PW. We can save the stack information to the String object with the last PrintStackTrace () method. As long as you capture stack information in the String object, we can easily use this information anywhere in your application. The following code snippet demonstrates the specific implementation steps:
private String getStackTraceAsString (Exception e) {// StringWriter stack information including StringWriter stringWriter = new StringWriter (); // must be packaged as StringWriter PrintWriter object, // to meet the requirements of printStackTrace PrintWriter printWriter = new PrintWriter (stringWriter); / / Get stack information E.PrintStackTrace (PrintWriter); // Convert to String, and return to this stringbuffer error (); return error.tostring ();}