Reading stack traces from top to bottom
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A ShopLite customer gets a 500 error, and the log shows 150 lines of red text. It looks like a wall, but it is a precise report. Read it in a fixed order and most bugs point to one line.
Exception type, message and the top frame
A stack trace is the report Java prints when an exception is not caught: the exception's type, its message, and the call stack at the moment it was thrown, one at line per frame, newest first.
In Example 1, booking a seat twice throws an IllegalStateException that nothing catches. The program stops, and Java prints the trace under the three normal output lines.
Example 1 · A stack trace from your own exception
import java.util.HashSet;import java.util.Set;
public class SeatBookingCrash { static Set<String> booked = new HashSet<>();
static void bookSeat(String seat) { if (!booked.add(seat)) { throw new IllegalStateException("Seat " + seat + " is already booked"); } System.out.println("Booked " + seat); }
static void bookGroup(String... seats) { for (String seat : seats) { bookSeat(seat); } }
public static void main(String[] args) { bookGroup("S4-31", "S4-32"); bookGroup("S4-33", "S4-32"); System.out.println("All groups booked"); }}Booked S4-31 Booked S4-32 Booked S4-33 Exception in thread "main" java.lang.IllegalStateException: Seat S4-32 is already booked at SeatBookingCrash.bookSeat(SeatBookingCrash.java:9) at SeatBookingCrash.bookGroup(SeatBookingCrash.java:16) at SeatBookingCrash.main(SeatBookingCrash.java:22)
What this code does
- The first three lines are normal output. Then
bookSeatthrows, nothing catches it, and Java prints the trace and ends the program, soAll groups bookednever appears. - Read from the top: type and message, then
bookSeatline 9 (thethrow), then the callers. Fixing it means deciding what a double booking should do (Practice 1).
Exception in thread "main" means the exception ended the main thread. Read the first line first: the type says what kind of problem it is (IllegalStateException: the program is in a state where this action is not allowed), and the message says which value caused it.
The first at line, the top frame, is the line that threw: bookSeat, line 9. The lines below answer "who called it?": bookGroup at line 16, called by main at line 22.
Finding the first frame in your own code among library frames
The first frame from your own code is the first at line, reading from the top, whose class you wrote. It is the line where your program handed a library a value it could not handle.
In Example 2, sorting the marks crashes deep inside the JDK. Eight of the ten frames are JDK code, so the top frame does not point at your mistake.
Example 2 · An exception thrown deep inside the JDK
import java.util.ArrayList;import java.util.Comparator;import java.util.List;
public class MarksSortCrash { public static void main(String[] args) { // "roll:marks" from the class sheet; AB means absent List<String> rows = new ArrayList<>(List.of("21:78", "22:91", "23:AB", "24:64")); rows.sort(Comparator.comparingInt(row -> Integer.parseInt(row.split(":")[1]))); System.out.println("Topper first: " + rows); }}Exception in thread "main" java.lang.NumberFormatException: For input string: "AB" 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 MarksSortCrash.lambda$main$0(MarksSortCrash.java:9) at java.base/java.util.Comparator.lambda$comparingInt$7b0bb60$1(Comparator.java:494) at java.base/java.util.TimSort.countRunAndMakeAscending(TimSort.java:360) at java.base/java.util.TimSort.sort(TimSort.java:220) at java.base/java.util.Arrays.sort(Arrays.java:1308) at java.base/java.util.ArrayList.sort(ArrayList.java:1804) at MarksSortCrash.main(MarksSortCrash.java:9)
What this code does
- Eight of the ten frames are JDK code (
java.base/...). They show the path, not the mistake:parseIntwas given"AB". MarksSortCrash.lambda$main$0is the comparator lambda on line 9, the first frame from your own code;mainon line 9 is the call tosort.
Start at your first frame and read the message: the value was "AB", so the comparator cannot handle an absent student.
Predict the output
Pick the frame to open
A ShopLite cart request crashed. Read the trace and choose the frame.
Round 1 of 2
Which frame do you open first?
Integer.java:662 change between Java versions, so a classmate on another JDK sees different numbers there. Your own frames keep the same line numbers.Caused by chains and '... n more'
The root cause is the last Caused by in a stack trace: the first thing that went wrong. Every exception above it was created by code that caught the older one and threw a new one.
In Example 3, each catch wraps the exception in a clearer one. The trace prints the newest exception first, then each older one under Caused by:.
Example 3 · A Caused by chain with '... n more'
import java.util.HashMap;import java.util.List;import java.util.Map;
public class FeeSettingsCrash { static int parseFee(String name, String value) { try { return Integer.parseInt(value); } catch (NumberFormatException e) { throw new IllegalArgumentException("Bad fee for " + name + ": " + value, e); } }
static Map<String, Integer> loadFees(List<String> lines) { Map<String, Integer> fees = new HashMap<>(); for (String line : lines) { String[] parts = line.split("="); fees.put(parts[0], parseFee(parts[0], parts[1])); } return fees; }
static Map<String, Integer> startApp(List<String> lines) { try { return loadFees(lines); } catch (IllegalArgumentException e) { throw new IllegalStateException("Could not load fee settings", e); } }
public static void main(String[] args) { List<String> lines = List.of("tuition=85000", "hostel=42,000", "transport=36000"); System.out.println(startApp(lines)); }}Exception in thread "main" java.lang.IllegalStateException: Could not load fee settings at FeeSettingsCrash.startApp(FeeSettingsCrash.java:27) at FeeSettingsCrash.main(FeeSettingsCrash.java:33) Caused by: java.lang.IllegalArgumentException: Bad fee for hostel: 42,000 at FeeSettingsCrash.parseFee(FeeSettingsCrash.java:10) at FeeSettingsCrash.loadFees(FeeSettingsCrash.java:18) at FeeSettingsCrash.startApp(FeeSettingsCrash.java:25) ... 1 more Caused by: java.lang.NumberFormatException: For input string: "42,000" 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 FeeSettingsCrash.parseFee(FeeSettingsCrash.java:8) ... 3 more
What this code does
- Each
catchwraps the exception with a clearer message and passes the old one as the cause, so nothing is lost: the top says "could not load settings", the bottom says exactly which text failed. ... 3 moreunder the NumberFormatException means its last three frames areloadFeesline 18,startAppline 25 andmainline 33, already printed above.
A line such as ... 1 more means the remaining frames of that exception are the same as the bottom frames already printed above it, so Java does not repeat them. Here ... 1 more stands for main at line 33.
Read the chain like this:
- First line: what the caller finally saw (
Could not load fee settings). - Last Caused by: where the trouble started (
For input string: "42,000"). - First own frame under that root cause:
parseFee, line 8. Fix there, or fix the data.
Order of execution
Read a Caused by chain
Put the steps in the order that finds the cause fastest.
Helpful NullPointerException messages
A helpful NPE message is the text that Java 15 and later puts in a NullPointerException: it says what was null and what the code tried to do with it, such as Cannot invoke "String.substring(int, int)" because "room" is null.
In Example 4, a missing hostel room makes blockOf call substring on null. Compile it with and without -g and compare the two messages.
Example 4 · The same NullPointerException with and without -g
import java.util.Map;
public class HostelRoomCrash { static String blockOf(String room) { return room.substring(0, 1); }
public static void main(String[] args) { Map<String, String> rooms = Map.of("Asha", "A-101", "Ravi", "B-204"); String room = rooms.get("Meena"); System.out.println("Block: " + blockOf(room)); }}$ javac HostelRoomCrash.java $ java HostelRoomCrash Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.substring(int, int)" because "<parameter1>" is null at HostelRoomCrash.blockOf(HostelRoomCrash.java:5) at HostelRoomCrash.main(HostelRoomCrash.java:11) $ javac -g HostelRoomCrash.java $ java HostelRoomCrash Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.substring(int, int)" because "room" is null at HostelRoomCrash.blockOf(HostelRoomCrash.java:5) at HostelRoomCrash.main(HostelRoomCrash.java:11)
What this code does
rooms.get("Meena")returnsnull, andblockOfcallssubstringon it. The top frame isblockOfline 5, but the real cause is one frame lower:mainpassed a missing room.- Without debug information the parameter is called
<parameter1>; with-gthe message namesroom. Your IDE and Maven compile with debug information, so you normally see the names.
Example 5 · Helpful messages for fields, maps and arrays
import java.util.HashMap;import java.util.Map;
record Address(String city, String pincode) {}
class Customer { String name; Address address; // not filled in yet
Customer(String name) { this.name = name; }}
public class NpeMessagesDemo { static Map<String, Integer> stock = new HashMap<>(Map.of("BK-CLEAN", 30)); static Customer current = new Customer("Asha"); static int[] marks;
static void tryIt(String label, Runnable code) { try { code.run(); } catch (NullPointerException e) { System.out.println(label + ": " + e.getMessage()); } }
public static void main(String[] args) { tryIt("1", () -> System.out.println(current.address.city())); tryIt("2", () -> System.out.println(stock.get("BK-PRAG") + 1)); tryIt("3", () -> System.out.println(marks[0])); tryIt("4", () -> System.out.println(current.name.length() + current.address.pincode().length())); }}1: Cannot invoke "Address.city()" because "NpeMessagesDemo.current.address" is null 2: Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.Map.get(Object)" is null 3: Cannot load from int array because "NpeMessagesDemo.marks" is null 4: Cannot invoke "Address.pincode()" because "NpeMessagesDemo.current.address" is null
What this code does
- Each message names the exact
null: a field (current.address), the return value ofMap.get, or a static array. No guessing which part ofcurrent.address.city()was null. - Message 2 is unboxing:
stock.get("BK-PRAG")returnsnull, and adding 1 needsintValue(). Message 4 shows that Java names the firstnullit meets, here beforepincode()is ever called.
Local variable and parameter names need debug information in the class file. Plain javac leaves it out, so the message says "<parameter1>" or "<local4>"; javac -g, IntelliJ, VS Code and Maven include it, so you see "room". Fields, array names and method results are always named, as Example 5 shows.
These messages came in Java 14 behind a flag and are on by default from Java 15.
stock.get("BK-PRAG") + 1 fails inside an automatic intValue() call: unboxing a null Integer is a NullPointerException too.Long Spring stack traces: where to look first
In Example 6 a ShopLite request returns 500, and the server log shows over 25 frames. Only a few of them are yours.
Example 6 · A ShopLite 500 error and its Spring stack trace
Runs in: the shoplite-api Spring Boot project (an edited copy of ProductMapper)
// src/main/java/com/shoplite/product/ProductMapper.java (part)
static ProductResponse toResponse(Product product) { Category category = product.getCategory(); return new ProductResponse(product.getId(), product.getSku(), product.getName(), category.getId(), categoryName(category), product.getPrice(), // line 55 product.getStock(), product.isActive());}
/** The category with its parent in front. */private static String categoryName(Category category) { return category.getParent().getName() + " > " + category.getName(); // line 61}$ curl -i http://localhost:8080/api/v1/products/9
HTTP/1.1 500
Content-Type: application/problem+json
(other headers left out)
{"type":"https://shoplite.example/problems/internal-error","title":"Internal server error","status":500,"detail":"Something went wrong on our side. Please try again later.","instance":"/api/v1/products/9"}
Server log (./mvnw spring-boot:run on Java 21; Spring Security and Tomcat frames at the end left out):
2026-10-16T14:41:07.512+05:30 ERROR 18244 --- [shoplite-api] [nio-8080-exec-3] c.shoplite.common.GlobalExceptionHandler : Unexpected error on GET /api/v1/products/9
java.lang.NullPointerException: Cannot invoke "com.shoplite.category.Category.getName()" because the return value of "com.shoplite.category.Category.getParent()" is null
at com.shoplite.product.ProductMapper.categoryName(ProductMapper.java:61) ~[classes/:na]
at com.shoplite.product.ProductMapper.toResponse(ProductMapper.java:55) ~[classes/:na]
at com.shoplite.product.ProductService.get(ProductService.java:57) ~[classes/:na]
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:580) ~[na:na]
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:359) ~[spring-aop-7.0.9.jar:7.0.9]
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) ~[spring-aop-7.0.9.jar:7.0.9]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:158) ~[spring-aop-7.0.9.jar:7.0.9]
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:133) ~[spring-tx-7.0.9.jar:7.0.9]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:371) ~[spring-tx-7.0.9.jar:7.0.9]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:130) ~[spring-tx-7.0.9.jar:7.0.9]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-7.0.9.jar:7.0.9]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:719) ~[spring-aop-7.0.9.jar:7.0.9]
at com.shoplite.product.ProductService$$SpringCGLIB$$0.get(<generated>) ~[classes/:na]
at com.shoplite.product.ProductController.get(ProductController.java:82) ~[classes/:na]
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:580) ~[na:na]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:252) ~[spring-web-7.0.9.jar:7.0.9]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:184) ~[spring-web-7.0.9.jar:7.0.9]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117) ~[spring-webmvc-7.0.9.jar:7.0.9]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:934) ~[spring-webmvc-7.0.9.jar:7.0.9]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:853) ~[spring-webmvc-7.0.9.jar:7.0.9]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:86) ~[spring-webmvc-7.0.9.jar:7.0.9]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) ~[spring-webmvc-7.0.9.jar:7.0.9]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:866) ~[spring-webmvc-7.0.9.jar:7.0.9]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1000) ~[spring-webmvc-7.0.9.jar:7.0.9]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:892) ~[spring-webmvc-7.0.9.jar:7.0.9]
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:622) ~[tomcat-embed-core-11.0.24.jar:6.1]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:874) ~[spring-webmvc-7.0.9.jar:7.0.9]
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:710) ~[tomcat-embed-core-11.0.24.jar:6.1]What this code does
- The client only sees the safe 500 ProblemDetail; the details are in the server log, which
GlobalExceptionHandlerwrites with the request's method and path. - The first line and the first
com.shopliteframe give the answer:categoryNameat line 61, and the message saysgetParent()returnednull. Clean Code's category, Books, is a top-level category with no parent. - Everything below
ProductService.getis the journey of the request: the transaction proxy (the generatedSpringCGLIBclass andTransactionInterceptor), the controller, Spring MVC and Tomcat.
A request passes through Tomcat, Spring Security's filters, Spring MVC and proxies before it reaches your code, so most frames are not where the bug is. Read the trace in this order:
- The log line above the trace: which request failed (
Unexpected error on GET /api/v1/products/9). - The first line of the trace: exception type and message, then the last Caused by if there is a chain.
- The first
com.shopliteframe from the top. Skip generated proxy frames (class names containingSpringCGLIB),reflectframes and everything underorg.springframework,org.apacheandjakarta. - For a startup failure (APPLICATION FAILED TO START), the last Caused by usually names the missing bean, property or database.
Order of execution
Read a Spring trace
A 150-line trace is in the log. Put the reading steps in order.
Next step
Check your understanding
12 quick questions