Sub topic 8
Reading a Stack Trace
When an exception is not caught, Java stops the program and prints a block of text. This text is called a stack trace. A stack trace is a report that says what went wrong and which chain of method calls led to the problem.
Beginners often see a stack trace as a scary wall of red text. It actually tells you a lot. Once you can read one, you can usually find a bug in under a minute. This chapter shows you how.
What the "stack" in stack trace means
When one method calls another, Java has to remember where to come back to. It keeps this information on the call stack. The call stack is a list of the methods that are running right now, with the newest call on top.
Each entry on the call stack is called a frame. A frame records one method call and the line inside that method that is running.
Say main calls average, and average calls divide. The call stack then looks like this:
| Position | Frame | Meaning |
|---|---|---|
| Top | `divide` | The method running right now |
| Middle | `average` | Waiting for `divide` to return |
| Bottom | `main` | Waiting for `average` to return |
When an exception happens, Java takes a snapshot of this stack. The stack trace is that snapshot, printed as text.
A first stack trace
Here is a small program with a bug. It divides by zero. The comments show the line numbers, because the stack trace refers to them.
public class TraceDemo { // line 1
public static void main(String[] args) { // line 2
System.out.println("Starting"); // line 3
int result = average(10, 0); // line 4
System.out.println("Average: " + result); // line 5
} // line 6
// line 7
static int average(int total, int count) { // line 8
return divide(total, count); // line 9
} // line 10
// line 11
static int divide(int a, int b) { // line 12
return a / b; // line 13
} // line 14
} // line 15Save it as TraceDemo.java, then compile and run it:
javac TraceDemo.java
java TraceDemoThe output is:
Starting
Exception in thread "main" java.lang.ArithmeticException: / by zero
at TraceDemo.divide(TraceDemo.java:13)
at TraceDemo.average(TraceDemo.java:9)
at TraceDemo.main(TraceDemo.java:4)"Average:" is never printed. The exception stopped the program at line 13, so line 5 never ran.
The parts of a stack trace
Let's take the trace apart one piece at a time.
The first line: what went wrong
Exception in thread "main" java.lang.ArithmeticException: / by zeroThis line has three parts:
Exception in thread "main"tells you which thread failed. A thread is one path of execution in a program. Simple programs have only themainthread.java.lang.ArithmeticExceptionis the full name of the exception class. This tells you the kind of problem./ by zerois the message. The message is a short description that the code throwing the exception wrote. It is the same text thatgetMessage()returns.
Always read this line first. The type and the message often explain the bug before you look at anything else.
The "at" lines: where it went wrong
Each line starting with at is one frame. Here is the format:
at ClassName.methodName(FileName.java:lineNumber)So at TraceDemo.divide(TraceDemo.java:13) means "in the class TraceDemo, in the method divide, in the file TraceDemo.java, at line 13."
The order: newest call first
The frames are listed from the top of the stack down:
- The first
atline is where the exception was actually thrown. Here that is line 13,a / b. - Each line below it is the method that called the one above.
- The last
atline is where it all started. For a simple program that is usuallymain.
Read the trace from the top to find where it broke. Read it from the bottom to find how the program got there.
Library frames and finding your own code
Exceptions are often thrown inside Java's own classes. Then the top frames belong to the Java library, not to you.
public class ParseTrace {
public static void main(String[] args) {
int n = Integer.parseInt("42x");
System.out.println(n);
}
}Running this prints something like the following:
Exception in thread "main" java.lang.NumberFormatException: For input string: "42x"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.parseInt(Integer.java:778)
at ParseTrace.main(ParseTrace.java:3)The line numbers inside Integer.java depend on your Java version, so yours may differ.
The java.base/ prefix names the module, the bundle of the Java library that the class lives in. Frames with this prefix are part of Java itself. The bug is almost never in there.
A good habit is to scan down until you reach the first frame from your own code. Here that is ParseTrace.main(ParseTrace.java:3). Line 3 passes "42x" to parseInt, and that input is the problem.
Printing a stack trace yourself
A stack trace is not only printed when a program crashes. Every exception object holds its own stack trace, and you can print it from inside a catch block with printStackTrace().
public class CatchAndPrint {
public static void main(String[] args) {
try {
int[] scores = new int[3];
scores[5] = 100;
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
System.out.println("Program continues");
}
}Output:
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
at CatchAndPrint.main(CatchAndPrint.java:5)
Program continuesTwo things are different from the crash version:
- There is no
Exception in thread "main"prefix. That prefix is added only when nobody catches the exception. - The program keeps running, because the exception was caught.
printStackTrace() writes to standard error (System.err), while println writes to standard output (System.out). These are two separate output streams. Some terminals and IDEs show them in a different order or color, so the trace may not appear exactly where you expect.
Reading the trace from code
You can also inspect frames in code. getStackTrace() returns an array of StackTraceElement objects. Element 0 is the top frame, where the exception was thrown.
public class InspectTrace {
static int divide(int a, int b) {
return a / b;
}
public static void main(String[] args) {
try {
divide(1, 0);
} catch (ArithmeticException e) {
StackTraceElement top = e.getStackTrace()[0];
System.out.println("Class: " + top.getClassName());
System.out.println("Method: " + top.getMethodName());
System.out.println("File: " + top.getFileName());
System.out.println("Line: " + top.getLineNumber());
}
}
}Output:
Class: InspectTrace
Method: divide
File: InspectTrace.java
Line: 3Most of the time you will just read printed traces. Logging tools use these methods behind the scenes.
Edge cases you may see
| What you see | What it means |
|---|---|
| `(Unknown Source)` instead of a file and line | The class was compiled without debug information, so the line number is missing. |
| `Caused by: ...` | This exception wraps another one. A later chapter on exception chaining covers this. |
| `... 5 more` | The remaining frames are the same as frames already printed above, so Java skips them. |
| The same few frames repeated many times, ending in `StackOverflowError` | A method keeps calling itself without stopping (endless recursion). |
Exercises
Exercise
A program prints this stack trace. Which method threw the exception, and which method started the chain of calls? Exception in thread "main" java.lang.NullPointerException at Shop.total(Shop.java:21) at Shop.checkout(Shop.java:12) at Shop.main(Shop.java:5)
Show answer
The top frame shows where the exception was thrown, so Shop.total threw it at line 21 of Shop.java. The bottom frame shows where the calls began, which is Shop.main at line 5. main called checkout at line 5, and checkout called total at line 12.
Exercise
In this trace, which line should you open first to look for your bug, and why? Exception in thread "main" java.lang.NumberFormatException: For input string: "abc" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67) at java.base/java.lang.Integer.parseInt(Integer.java:662) at java.base/java.lang.Integer.parseInt(Integer.java:778) at Survey.readAge(Survey.java:14) at Survey.main(Survey.java:6)
Show answer
Open Survey.java at line 14, inside readAge. The first three frames have the java.base/ prefix, so they are Java library code. Survey.readAge is the first frame from your own code, and it is where the text "abc" was passed to Integer.parseInt.
Exercise
In TraceDemo, the exception is thrown on line 13, but the bug is not on that line. Where is the bug, and how does the stack trace help you find it?
Show answer
Line 13 (return a / b;) does the division correctly. The bug is on line 4, where main calls average(10, 0) with a count of zero. The stack trace lists main at line 4 as the bottom frame. Reading the frames upward (main line 4, then average line 9, then divide line 13) shows how the zero travelled from main into divide.