Delphi Clinic C++Builder Gate Training & Consultancy Delphi Notes Weblog Dr.Bob's Webshop
Hubert Klein Ikkink (aka Mr.Haki) - Communications Officer
 Mr.Haki's JBuilder Jar #62
See Also: JBuilder Papers

Exception stack trace
Handling exceptions is easy in Java. We must use the try .. catch (.. finally) statements to handle exceptions. In the catch block we usually handle the exception by printing the exception to a log file for example.
The Exception class contains a method printStackTrace() method, which prints a stack trace from the method in which the exception occurred. The stack trace is printed to the System.err printstream. But sometimes we want to print the stack trace to something else then the System.err printstream. For example use it in an e-mail when an exception occurs, or in a dialog window of an application.

The printStackTrace() method has different signatures:

We can use the last method to store the stack trace in a String object. Once we have captured the trace in the String object, we can easily use it elsewhere in our applications.

The following piece of code shows how we can achieve this:

private String getStackTraceAsString() {
    //
    // StringWriter will contain text of stack trace
    //
    StringWriter stringWriter = new StringWriter();

    //
    // Need to encapsulate the StringWriter into a Printwriter object
    // to fill up with stack trace
    //
    PrintWriter printWriter = new PrintWriter(stringWriter);

    //
    // Get the stack trace and fill the PrintWriter
    //
    e.printStackTrace(printWriter);

    //
    // StringBuffer to hold stack trace
    //
    StringBuffer error = stringWriter.getBuffer();
    
    //
    // Return String object with stack trace
    //
    return error.toString();
}

The StringBuffer object error contains the complete stack trace. We can convert is to a String object, by using the toString() method.

The following sample application will result in the following output:

TRACE = java.lang.ArithmeticException: / by zero
	at com.drbob42.jbjar.tip62.Tracer.divide(Tracer.java:17)
	at com.drbob42.jbjar.tip62.Tracer.main(Tracer.java:12)

Personally I use this method often in servlet programming. I include the stack trace in an error page of the application, but it is encapsulated in HTML comment tags. This way the user cannot see it, but by looking at the HTML source I can still see it and use it for debugging purposes.


This webpage © 1997-2009 by Bob Swart (aka Dr.Bob - www.drbob42.com). All Rights Reserved.