Learn how to print a stack trace to debug Java exceptions

Learn Java at
Developer's Daily Pure Java Department

 

Introduction

Oftentimes when you generate an exception in a Java program, you just print the exception to standard output, using a code sequence like the one shown in Listing 1. I typically see this done when developers are debugging Java programs.

 
try {

    // you "try" something here


catch (IOException e) {

    // you handle the exception here
    System.out.println("Got an IOException: " + e.getMessage());

}

 
Listing 1:   This snippet of Java code shows how to print the message of an exception, using Java's e.getMessage() method.
 

Again, you probably don't handle your errors like this in a live Java application, but you might do it during the development and debugging process.

Here's the output you'd get from the println statement above if a program using this code snippet tried to open a file named fred.txt, and the file didn't exist:

 

Creating a better error message for debugging:   e.printStackTrace()

Instead of using Java's e.getMessage() method to print errors during the debugging process, you can get more information about the error process if you print a stack trace from the exception.  The snippet of source code shown in Listing 2 shows how to print the stack trace with Java's e.printStackTrace() method:

 
try {

    // try to open the non-existent "fred.txt" here

}
catch (IOException e) {

    // you handle the exception here
    e.printStackTrace();

}

 
Listing 2:   This snippet of code shows how to print an entire stack trace using Java's e.printStackTrace() method.
 

Using this code snippet when trying to open a non-existent file named fred.txt, you'll get this output message:

In the process of debugging programs, I'll take these five lines of output any day, compared to the simple error message shown after Listing 1!

As a final point - don't forget the e.getMessage() method.  You'll probably use it more often in production programs, because the error message is not automatically printed to the screen.  Instead, you can print it wherever you like - such as in a dialog window of a graphical application.
 

Download our test code

Click here if you'd like to download the small ExTest.java program we used to generate the error output shown above.  After the source code appears in your browser, simply save the code to your local filesystem by selecting the File | Save As .. option of your browser.
 

Click here to return to
Developer's Daily Pure Java Department


What's Related


Copyright 1998-2008 DevDaily Interactive, Inc.
All Rights Reserved.