Java stack trace - How to print a stack trace to debug Java exceptions

Java stack trace FAQ: How can I print a Java stack trace to debug an exception?

Many times 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 (above): This snippet of Java code shows how to print the message of an exception, using Java's 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:

Got an IOException: fred.txt

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 (above): This snippet of code shows how to print an entire stack trace using Java's printStackTrace() method.

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

java.io.FileNotFoundException: fred.txt
        at java.io.FileInputStream.<init>(FileInputStream.java)
        at java.io.FileInputStream.<init>(FileInputStream.java)
        at ExTest.readMyFile(ExTest.java:19)
        at ExTest.main(ExTest.java:7)

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

Post new comment

The content of this field is kept private and will not be shown publicly.