How do I get an exception stack trace message?

Category: java.io, viewed: 11145 time(s).

In this example we use the StringWriter and PrintWriter class to convert stack trace exception message to a string.

package org.kodejava.example.lang;

import java.io.StringWriter;
import java.io.PrintWriter;

public class StackTraceToString {
    public static void main(String[] args) {
        try {
            int a = 10 / 0;
        } catch (Exception e) {
            //
            // Create a StringWriter and a PrintWriter both of these object
            // will be used to convert the data in the stack trace to a string.
            //
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);

            //
            // Instead of writting the stack trace in the console we write it
            // to the PrintWriter, to get the stack trace message we then call
            // the toString() method of StringWriter.
            //
            e.printStackTrace(pw);

            System.out.println("Error = " + sw.toString());
        }
    }
}
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Uncensored Newsgroups
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Java Training

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats