Reading a stack trace
A stack trace is the list of calls that led to a failure, printed from the innermost frame outward. Every Java programmer reads dozens a week and most of the time only the first two lines and the first frame matter. This lesson prints a real trace, takes one apart from inside the program, and shows the Caused by chain a wrapped exception produces.
A trace the JVM prints
An exception that nothing catches ends the thread, and the JVM prints its trace to the standard error stream. The program below calls two methods and fails in the second one at an index past the end of an array:
public class Uncaught {
public static void main(String[] args) {
System.out.println("before");
level2();
System.out.println("after");
}
static void level2() {
level1(3);
}
static void level1(int n) {
int[] values = new int[2];
values[n] = 1;
}
}
javac -Xlint:all Uncaught.java
java Uncaught
echo "status: $?"
before
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 2
at Uncaught.level1(Uncaught.java:14)
at Uncaught.level2(Uncaught.java:9)
at Uncaught.main(Uncaught.java:4)
status: 1
The first line names the thread, the class of the exception and its message. Then one line per frame, innermost first: level1 at line 14 is where the failure happened, level2 at line 9 called it, and main at line 4 called that. The after line never printed, because the exception left main, and the shell saw status 1.
Reading the frames
The trace is data: getStackTrace answers an array of StackTraceElement, each with a class, a method, a file and a line. The program reads the top two frames of a caught exception:
public class Frames {
public static void main(String[] args) {
try {
deeper();
} catch (IllegalStateException e) {
StackTraceElement[] frames = e.getStackTrace();
System.out.println("frames: " + frames.length);
StackTraceElement top = frames[0];
System.out.println("top: " + top.getClassName() + "." + top.getMethodName()
+ " line " + top.getLineNumber());
System.out.println("caller: " + frames[1].getClassName() + "." + frames[1].getMethodName()
+ " line " + frames[1].getLineNumber());
}
}
static void deeper() {
throw new IllegalStateException("from deeper");
}
}
javac -Xlint:all Frames.java
java Frames
frames: 2
top: Frames.deeper line 17
caller: Frames.main line 4
Two frames, because the exception was created in deeper and caught in main, and the line numbers are the ones a person would find in the editor. A program may walk the array, which is how a framework prints a filtered trace with its own frames removed.
Caused by
A wrapped exception prints two traces: the wrapper's, then Caused by and the original. The program catches the wrapper and prints its trace into a string, so the whole text appears on the standard output:
import java.io.PrintWriter;
import java.io.StringWriter;
public class Caused {
static class ConfigException extends Exception {
private static final long serialVersionUID = 1L;
ConfigException(String message, Throwable cause) {
super(message, cause);
}
}
public static void main(String[] args) {
try {
load("bad");
} catch (ConfigException e) {
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
System.out.println(writer);
}
}
static int load(String text) throws ConfigException {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
throw new ConfigException("cannot load port from " + text, e);
}
}
}
javac -Xlint:all Caused.java
java Caused
Caused$ConfigException: cannot load port from bad
at Caused.load(Caused.java:27)
at Caused.main(Caused.java:15)
Caused by: java.lang.NumberFormatException: For input string: "bad"
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 Caused.load(Caused.java:25)
... 1 more
Two details of the text are worth knowing. The class name is Caused$ConfigException with a dollar, because the exception is a nested class and that is its binary name. And the last line of the second trace is ... 1 more, which replaces the frames the two traces share; the full list is longer than the text, and the JVM prints the difference only.
The chain is the reason to keep the cause of lesson 099: without it the second trace is missing, and the first one names a line of this program that did nothing wrong. The frames in java.base are the JDK's own code and are usually skipped by a reader.
What to read first
Read the first line for the type and the message, which say what broke and with what value. Read the first frame that belongs to your own code, which is where the call came from and usually where the mistake is. Read Caused by if there is one, because the outermost message is often the summary and the innermost is the fact. And read the line number, not the method name alone: the same method may be called from ten places.
A trace longer than a screen is usually a recursion or a framework. For a recursion the pattern of repeated frames is the answer, and StackOverflowError of lesson 102 is the extreme case. For a framework the top frames are proxies and filters, and the frame with a class name from the project is the place to start.
Exercises
- Add a third method between main and level2 and count the frames of the new trace.
- Catch the exception of Uncaught and print only the top frame with getStackTrace()[0].
- Remove the cause from ConfigException and compare the two traces.
- Print the file name and the line number of every frame of Frames in one line.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which frame of a stack trace is the innermost call?
Answer
The first one, just under the exception line
The trace is printed from where the exception was created outward to the entry point.
-
What does the first line of a trace contain?
Answer
The thread, the class of the exception and its message
The type says what failed and the message says with what value.
-
What does
Caused byshow?Answer
The original exception of a wrapper, with its own frames
The cause chain is printed under the wrapper, and the shared frames are cut.
-
What does this program print?
public class Q1 { static void a() { b(); } static void b() { throw new IllegalStateException("boom"); } public static void main(String[] args) { try { a(); } catch (IllegalStateException e) { System.out.println(e.getStackTrace().length); System.out.println(e.getStackTrace()[0].getMethodName()); } } }Answer
3 / b
The trace holds the three frames of b, a and main, and the first is where the exception was made.
-
Why does a trace of a nested class show a dollar in the name?
Answer
It is the binary name of the nested class, with $ between the parts
The class file is named Outer$Inner, and the trace prints the name of the class file.
-
What does
... 1 moreat the end of a Caused by trace mean?Answer
One frame was shared with the trace above and is not repeated
The printer removes the common tail of the two traces and states how many frames it dropped.
-
Which part of a long trace names the mistake?
Answer
The first frame that belongs to the project code
The JDK frames say what called the code, and the project frame says where the call came from.
-
What does this program print?
public class Q2 { public static void main(String[] args) { try { throw new RuntimeException("x"); } catch (RuntimeException e) { System.out.println(e.getStackTrace()[0].getClassName()); System.out.println(e.getStackTrace()[0].getMethodName()); } } }Answer
Q2 / main
The exception was created in main, which is the first frame of the trace.
-
What does this program print?
public class Q3 { static int fail() { throw new IllegalStateException("bad"); } public static void main(String[] args) { try { fail(); } catch (IllegalStateException e) { System.out.println(e.getMessage()); System.out.println(e.getStackTrace().length); } } }Answer
bad / 2
The message is bad and the trace holds the frames of fail and main.
-
What does
printStackTracewrite to when it is given a PrintWriter?Answer
The writer, so the trace can be captured or sent to a log
The writer form is how a program puts a trace into a log or a response body.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev