Role of StringWriter/PrintWriter in Java output exception information

Source: Internet
Author: User

Let's take a look at the source code of JUnit. At the beginning, I found a piece of interesting code:

public String trace() {        StringWriter stringWriter = new StringWriter();        PrintWriter writer = new PrintWriter(stringWriter);        thrownException().printStackTrace(writer);        StringBuffer buffer = stringWriter.getBuffer();        return buffer.toString();    }

I have never touched StringWriter or PrintWriter before. Curious about this. In fact, Java IO is complicated, because the IO parameter types required by interfaces provided by many classes are fixed, while the data we master or need to input is many encapsulation types, therefore, encapsulation is often required. (I have little experience with I/O)

Check the Java API documentation and find the following:

voidprintStackTrace()           Prints this throwable and its backtrace to the standard error stream. voidprintStackTrace(PrintStream s)           Prints this throwable and its backtrace to the specified print stream. voidprintStackTrace(PrintWriter s)           Prints this throwable and its backtrace to the specified print writer.

From the above information, we can see that there are three types of error inputs for Throwable (a base class inherited by Exception). printStackTrace () refers to outputting the Exception itself and Exception information to the standard error stream; printStatckTrace (PrintStream s) is used to output the exception itself and exception information to the PrintStream object. The third is output to PrintWriter.

In normal cases, if we use IDE, errors are usually directly output to the Console, but sometimes we need to output exception information to the file or other webpages, in this case, two APIs with parameters are required.

There are many constructors using PrintWriter and PrintWriter. I use StringWriter as the construction parameter.

To verify the feasibility. Write a small program and run it.

Import java. io. printWriter; import java. io. stringWriter; @ SuppressWarnings ("serial") public class MyException extends Exception {public String getPrintStackTraceAsString () {StringWriter sw = new StringWriter (); PrintWriter pw = new PrintWriter (sw ); printStackTrace (pw); // enter the exception information in pw (PrintWriter) StringBuffer sb = sw. getBuffer (); return sb. toString ();}}

Public class TestException {public static void main (String [] args) {try {throw new MyException ();} catch (MyException e) {// because the implemented method is defined in MyException, the catch parameter cannot be converted to ExceptionSystem. out. println ("I am not an average Exception:" + e. getPrintStackTraceAsString (); // e. printStackTrace ();}}}

When the e. printStackTrace () method is used, the following results are obtained:

MyException
At TestException. main (TestException. java: 4)


When we use the defined method: <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + forward + cjxwpjxpbwcgc3jjjpq = "" alt = "">

Code: https://github.com/louiscai/StringWriterWithPrintWriter

==================================== End of the body ======================= =



In addition:

1) Throwable itself also has the getStackTrace () method.

2) The difference between PrintWriter and PrintStream can be referred to: http://hi.baidu.com/shdren09/item/8b1d2631e78b7abf623aff3f

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: 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.