A stack trace (or traceback) is an output that shows the method stack of your application. You’ll typically see one on your terminal when your application encounters an error.
As the name suggests, a stack data structure stores the methods in a stack trace. The method where program execution begins is at the bottom of the stack while the one that produces the stack trace is at the top.
A stack trace can be very useful when you’re debugging your code.
Why Is a Stack Trace Important?
A stack trace is an important debugging tool. It gives you detailed information such as the type of error, the method in which it occurred, the line in your code where it occurred & the file path.
To a seasoned programmer, this information is a goldmine for understanding what exactly went wrong and where.
As a programmer, you can also ask your program to create a stack trace on demand. This can be particularly useful for code maintenance and troubleshooting.
How to Output a Stack Trace
Depending on your compiler version, you’ll most likely get a readable traceback. A readable traceback provides user-friendly text about the error, unlike the normal traceback. This is especially true for new compilers. Therefore, the best way to learn about stack traces is to produce one yourself.
You can produce a stack trace without having any errors in your code. To do so, simply use the dumpStack method of the java.lang.Thread class. It will show all methods that have been called, right from the one that calls dumpStack. The calling method will be the one on top of the stack data structure.
Here’s an example program that explicitly generates a stack trace:
class StackTraceDemo {
public static void main(String[] args) {
day();
}
static void day() {
hours();
}
static void hours() {
minutes();
}
static void minutes() {
int a = 24 * 60;
System.out.println(a + " minutes in a day");
Thread.dumpStack();
}
}
Output:
1440 minutes in a day
java.lang.Exception: Stack trace
at java.base/java.lang.Thread.dumpStack(Thread.java:138)
at StackTraceDemo.minutes(StackTraceDemo.java:17)
at StackTraceDemo.hours(StackTraceDemo.java:11)
at StackTraceDemo.day(StackTraceDemo.java:7)
at StackTraceDemo.main(StackTraceDemo.java:3)
In this output, you can observe that the traceback shows how the program called each Java method and at what line number in its source code. The method that generated the stack trace is the one shown at the top of the stack. The method that called that one is on the line below it, and so on.
Beyond the Stack Trace
By default, when your Java program runs into an error it will halt and display a stack trace. However, you can choose to handle these errors gracefully instead of showing messages that may confuse end users.
You can improve your program’s error handling by using a try...catch() block to capture exceptions. It’s also important to consider—and understand—the various types of errors your programs may encounter.