Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 06 / Topic 7 of 8

Reading a stack trace

A stack trace is Java showing you the chain of method calls that led to the exception. Read it top to bottom:

  • The first line (Exception in thread "main" ...) is the exception's type and message — start here, it usually tells you exactly what went wrong.
  • Each line starting with at is one stack frame: a method call, most recent first. The top at line is where the exception object was actually created (often inside a JDK method you didn't write). Each line below it is "which method called that one."
  • The bottom at line is where the chain started — usually main.
  • The file name and line number in parentheses (StackTraceAnatomy.java:14) tell you exactly where to look in your own code. JDK-internal frames (lines starting with java.base/..., as in section 1's NumberFormatException) are rarely where the bug is; skip down to the first frame that names one of your own files.

examples/StackTraceAnatomy.java makes the chain obvious with four nested methods: main calls level1, which calls level2, which calls level3, which divides by zero.

static int level3(int balance, int amount) {
    return balance / amount;   // throws ArithmeticException when amount is 0
}
static int level2(int balance, int amount) { return level3(balance, amount); }
static int level1(int balance, int amount) { return level2(balance, amount); }

Real output:

$ javac StackTraceAnatomy.java
$ java StackTraceAnatomy
Calling level1(5000, 0), which ends in a divide-by-zero...
  level1: asking level2 for balance/amount
  level2: asking level3 for balance/amount
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at StackTraceAnatomy.level3(StackTraceAnatomy.java:14)
	at StackTraceAnatomy.level2(StackTraceAnatomy.java:19)
	at StackTraceAnatomy.level1(StackTraceAnatomy.java:24)
	at StackTraceAnatomy.main(StackTraceAnatomy.java:29)

Top to bottom: the division happened inside level3 at line 14; level3 was called by level2 at line 19; level2 was called by level1 at line 24; level1 was called by main at line 29. Four frames, one clear path back to the mistake (level1(5000, 0) — asking for balance / 0).

Full program: examples/StackTraceAnatomy.java.

Done here? The practice set for Part 6 — including the solutions — is on the part page.

Search the guide