Java: Saves the complete stack trace information for an exception to a string (detailed) __java

Source: Internet
Author: User

In Java development, we often have to deal with various exceptions, we typically get exception information with e.tostring () or e.getmessage (), but sometimes there is a lot of information in the exception stack, such as throwing an exception with the following code: Try{
Code throws Someexception
} Catch(Someexception e) {
Throw NewMyException ("Caught some exception", e);
In this case, the e.tostring () or e.getmessage () is not able to get all the information, only to get the contents of the top of the stack, the Java API is clearly stated:
At this point we can print stack trace information using the E.printstacktrace () method, but the view API will find that this method simply prints the stack to the standard error output stream of the system:
If our business logic processing needs to show the stack information to the user, we need to get all the information on the stack, view the source of the Printstacktrace () method, and we find that it is actually invoking an overloaded method: Public voidPrintstacktrace () {
Printstacktrace (System.err);
Looking at the API for the Throwable class, we found three overloaded methods:
The second overloaded method writes the data to the stream in byte, such as System.out, System.err. The third overloaded method can output the stack information to a writer, where we use a subclass of writer StringWriter to build the string: StringWriter SW = NewStringWriter ();
PrintWriter PW = NewPrintWriter (SW, True);
E.printstacktrace (PW);
String stacktracestring = Sw.getbuffer (). toString ();

To simplify, you can encapsulate this piece of code within a public static method for easy invocation:
Public StaticString printstacktracetostring (Throwable t) {
StringWriter SW = NewStringWriter ();
T.printstacktrace ( NewPrintWriter (SW, True));
returnSw.getbuffer (). toString ();

Related Article

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: and provide relevant evidence. A staff member will contact you within 5 working days.

Tags Index: