Reading Stack Traces

When an exception escapes, Java prints its type, message, and a stack trace. The trace is a history of active method calls at the failure point.

Read from the top. Find the first frame that belongs to your code, open that file and line, then inspect the values that reached it.

A real failure

This program sends nonnumeric text to Integer.parseInt:

public class StackTraceProbe {
    static int parseScore(String text) {
        return Integer.parseInt(text);
    }

    public static void main(String[] args) {
        parseScore("ninety");
    }
}

The report on standard error:

Exception in thread "main" java.lang.NumberFormatException: For input string: "ninety"
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
	at java.base/java.lang.Integer.parseInt(Integer.java:565)
	at java.base/java.lang.Integer.parseInt(Integer.java:662)
	at StackTraceProbe.parseScore(StackTraceProbe.java:3)
	at StackTraceProbe.main(StackTraceProbe.java:7)

The trace starts with three Java library frames. The next frame is StackTraceProbe.parseScore at line 3, where our input entered the failing library call. The final frame points to main at line 7.

Library frames provide context, but the first application frame is usually the fastest place to begin. Calls below it show how execution arrived there.

The line that throws can be a symptom rather than the original cause. Trace bad input backward after locating the immediate failure.

Use the question below to choose the right starting frame in a trace.