Lesson · Exception Handling
Stack traces: reading them like a map
15 min readStack Traces & Diagnostics
A stack trace is recorded at construction, read top-down: the first frame is where it was thrown, the frames below are the callers. Caused by chains carry translations, fillInStackTrace costs money, and stackless exceptions skip the recording.
Where did it actually happen?
One chain of calls, one throw, and a trace that answers a precise question: which line, inside which method, first failed?
static void a() { b(); } static void b() { c(); } static void c() { throw new IllegalStateException("boom"); } // caught in main: // origin: c <- the frame that threw (top of the trace) // caller: b <- the frame below: who called c // frames: 4 <- c, b, a, main
Predict: the trace is recorded at construction, from the throw point outward. The first frame is the origin, and each frame below is one caller up the stack; teaching materials sometimes say 'read bottom-up', which locates main, but the story starts at the top.
The parts of a trace
Every trace is built from the same pieces:
| Part | Looks like | Tells you |
|---|---|---|
| Header | java.lang.IllegalStateException: boom | Type and message: what kind of failure, described by the thrower |
| Frames | at app.Service.c(Service.java:14) | Class, method, file and line: where the code was, one frame per call |
| Elision | ... 23 more | Frames omitted between library calls; the count is honest, the detail is not expanded |
Caused by: chain | Caused by: java.io.IOException: ... | The translated original: from the custom-exceptions lesson, verbatim |
| Suppressed | Suppressed: ... | Cleanup failures attached by try-with-resources, each with their own mini-trace |
One trace, several stories. Header for what, frames for where, caused-by for the older failure underneath, suppressed for the cleanup that also broke; a complete report has all of them, which is why neither wrapping nor resources should drop them.
Tools and cost
Three programming interfaces matter, and one performance fact:
printStackTrace()prints to standard error: fine for exercises, wrong for production where logging should own output and format.getStackTrace()returns the frames as an array: index 0 is the origin; the verified demo reads methodscandbstraight out of it.StackWalker(Java 9+) walks frames lazily, with control over class references: the modern tool for inspection and callers-of APIs.- Cost: every
newof a throwable fills in its stack trace by walking the stack, which can dominate cost in hot paths: reuse, or skip capture when the trace is not needed. - Stackless exceptions: overriding
fillInStackTrace()to returnthisproduces an exception with zero frames, verified atlength 0, for control-flow-style or performance-sensitive paths where location is known.
Exceptions are expensive mostly because traces are honest. The JVM records where the object was constructed, not where it was thrown; skipping that recording is a deliberate, documentable trade.
Trace desk · the map, annotated
pick a partAnnotated snippet
How to read it
Type and message: what kind of failure, described by the thrower at the moment of the throw.
A complete message here shortens every investigation; the thrower knew the facts first.
The origin-frame and frame-count values were verified by the lesson's demo; the stackless entry by a zero-length capture run.
The trace-reading playbook
Facing a trace in a log, in order:
- Read the header: type and message name the failure before any frame matters.
- Find the first frame that belongs to your code: that is where the story starts; library frames above it are where the failure surfaced through.
- Follow
Caused bydownward until the chain ends: the last cause is the original failure, and the chain's order is construction order. - Scan for
Suppressedwhen cleanup ran: body and close failures travel together. - Before adding traces to a hot path, remember the recording cost; skip with
fillInStackTraceoverride when location is irrelevant.
A trace is a recorded map, not a mystery. Type, message, origin, callers, causes, suppressed: reading in that order turns a wall of at lines into a route from symptom to source.
Recorded at construction, read top-down, traced back through causes
The first frame is the throw origin; frames below are the callers; Caused by chains reconstruct translated failures and Suppressed entries record cleanup that also broke. fillInStackTrace is why exceptions cost, printStackTrace belongs in exercises, logging belongs in production, and stackless exceptions skip the recording when the location is known.
Interview angles
How do you read a stack trace efficiently?+
Header first (type and message), then the top frame as the origin, then the first frame that is yours; Caused by chains are read to the end for the original failure.
Frames above your code are where the exception surfaced through other layers; frames below are the callers that led there. The discipline is constant: what failed, where first, what called it, and what is under the translations.
at app.Service.c(Service.java:14) // origin at app.Service.b(Service.java:9) // caller at app.Service.a(Service.java:5) // caller's caller
Common misconception: That 'read bottom-up' is the rule to remember. Locating main that way is a habit; the narrative starts at the top frame and follows the callers down.
Follow-up: Which frame do you open first when reviewing someone else's bug report?
What is the cost model of exceptions, precisely?+
Construction is the expensive part, because the JVM walks the stack and records every frame (fillInStackTrace); throwing and catching themselves are comparatively cheap.
That is why 'exceptions are slow' is really 'stack capture is slow': a reused exception or a stackless one is far cheaper. Hot paths that throw regularly for control flow pay the walk on every construction, which profiling shows clearly.
// skip capture when the origin is known and irrelevant: @Override public Throwable fillInStackTrace() { return this; }
Common misconception: That catch blocks are the bottleneck. The recording at construction is; catching is a table lookup and an unwind.
Follow-up: Where do frameworks reuse exceptions, and what does that trade away?
When is a stackless exception legitimate?+
When the failure is expected, frequent and the origin is already known by construction, so the trace adds cost without information: internal control signals, cached failures, deliberately cheap guard throws.
Verified in this lesson: overriding fillInStackTrace to return this yields getStackTrace().length == 0. The trade must be deliberate: debugging such an exception later means adding context to the message, because the map is gone.
throw new StacklessException("known origin"); // zero frames recorded
Common misconception: That stackless exceptions are a standard optimisation. They lose the diagnostic that exceptions exist for, so they stay exceptional.
Follow-up: What must the log line carry to compensate for zero frames?
Why does a trace show 'Caused by' and 'Suppressed'?+
Caused by marks translations: the wrapped original, from the custom-exceptions pattern; Suppressed marks additional failures, chiefly cleanup from try-with-resources that failed while the primary exception was in flight.
Both sections carry their own frame lists, so a translated, resource-using failure produces one readable report: domain story on top, IO story underneath, cleanup failure attached. Dropping either in logging loses evidence the JVM carefully preserved.
Caused by: java.io.IOException: settings.xml missing Suppressed: java.lang.IllegalStateException: close failed
Common misconception: That Caused by is printed for decoration. It is where the actual root cause usually lives.
Follow-up: Which logging call preserves suppressed exceptions in one event?
What is StackWalker for?+
Lazy, controlled stack traversal introduced in Java 9: walk frames with filters and limits, inspect method names without materialising every frame, and access the callers of an API without capturing a throwable.
It replaces new Throwable().getStackTrace() tricks for 'who called me' features, and it can skip class references for performance and retention. getStackTrace on an exception still remains the way to inspect a recorded trace.
StackWalker.getInstance().walk(s -> s.limit(3).toList()); // nearest frames, lazily
Common misconception: That StackWalker replaces stack traces. Traces record a moment inside an exception; StackWalker inspects the live stack on demand.
Follow-up: Which API would you use to build a 'caller info' diagnostics line?