Skip to content
javahacks.dev
Debugging

How to Read a Java Stack Trace Correctly and Find the Cause

Read a Java stack trace from the top line down, follow Caused by chains to the root exception and ignore framework frames to find the line in your code.

7 min read
Summarize in AI
Flat illustration of a magnifier over lines of a log, with the OpenJDK, Apache Maven, JUnit5 and Gradle logos.

A stack trace is a record of what the program was doing when an exception was created. Everyone sees dozens a week and many read only the first line. The rest holds the answer. This post teaches the reading order on one realistic trace. It pairs with debugging in IntelliJ IDEA, and each exception class mentioned has its own fix post, such as NullPointerException.

A trace to read

Text
jakarta.servlet.ServletException: Request processing failed: java.lang.IllegalStateException: Cannot load customer 17
	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)
	at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:903)
	at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:564)
	... 41 more
Caused by: java.lang.IllegalStateException: Cannot load customer 17
	at dev.javahacks.shop.CustomerService.load(CustomerService.java:48)
	at dev.javahacks.shop.CustomerController.get(CustomerController.java:22)
	at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103)
	... 52 more
Caused by: java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available, request timed out after 30000ms
	at com.zaxxer.hikari.pool.HikariPool.createTimeoutException(HikariPool.java:709)
	at com.zaxxer.hikari.pool.HikariPool.getConnection(HikariPool.java:189)
	at dev.javahacks.shop.CustomerRepository.find(CustomerRepository.java:31)
	... 60 more

Step 1: the first line

ServletException: Request processing failed is a wrapper that says "something inside the request failed" and adds nothing else. The text after the colon repeats the next level. Do not stop here.

Step 2: find the last Caused by

Scan down to the final Caused by:. Here it is SQLTransientConnectionException: HikariPool-1 - Connection is not available.... That is the root: the connection pool had no free connection. The two exceptions above it were created to explain the failure at higher levels of the code. The fix for this root is in connection timeouts.

Some libraries wrap with a different message at each level, so read all the messages from the bottom up as a story: the pool timed out, so loading customer 17 failed, so the request failed.

Step 3: find your code

Within the root exception's frames, look for the first line in your package:

Text
at dev.javahacks.shop.CustomerRepository.find(CustomerRepository.java:31)

That is the call in your code that triggered the failing library call: line 31 of CustomerRepository. Frames above it (HikariPool.getConnection) belong to the library and show how it failed. The frames below show how your code got there. The IDE turns each frame into a link; click CustomerRepository.java:31.

Frame order

The most recent call is first. The first at line is where the exception object was created, and each following line is the caller of the one above. The last line is the start of the thread (Thread.run or a servlet container's worker). Read downward to see who called whom.

What the odd lines mean

LineMeaning
... 41 moreThis trace shares its remaining 41 frames with the enclosing trace; they are not repeated
Caused by:The next exception is the cause of the one above
Suppressed:An exception thrown while closing a resource, hidden behind the main one
<generated> or $$SpringCGLIB$$A proxy class created by a framework
Native MethodA call into native code
java.base/ prefixThe module the class belongs to
Unknown SourceNo debug info in the class

Suppressed appears with try-with-resources:

Text
java.io.IOException: write failed
	at ...
	Suppressed: java.io.IOException: close failed
		at ...

The main exception is the one to fix first, and the suppressed one tells you the close also failed.

Missing or trimmed traces

Some logging setups cut the trace after a number of frames; others print only e.getMessage(), which loses it entirely. Log the exception object: log.error("Failed to load customer {}", id, e); the last argument being the exception prints the full trace. A stack trace with no frames in your code means the failure began in a thread you did not start, such as a framework's scheduler; check what registered the task.

HotSpot may omit the trace for a frequently thrown exception that was compiled for speed (-XX:-OmitStackTraceInFastThrow turns it back on). If a NullPointerException shows without a trace after many repeats, that is why.

Reading a trace from production

Search for the first line number in the source version that was deployed, not the latest. A line number from a different version points at unrelated code. Keep release tags so you can check out what ran.

Produce a trace you can study

Reading gets faster with deliberate practice on a trace whose cause you know. This small program wraps a failure at three levels, like a real service does:

java
public class TraceDemo {

    public static void main(String[] args) {
        try {
            new OrderService().place("c-17");
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
    }

    static class OrderService {
        void place(String customerId) {
            try {
                new CustomerRepository().find(customerId);
            } catch (IllegalStateException e) {
                throw new RuntimeException("Cannot place order for " + customerId, e);
            }
        }
    }

    static class CustomerRepository {
        void find(String customerId) {
            try {
                Integer.parseInt("not-a-number");
            } catch (NumberFormatException e) {
                throw new IllegalStateException("Corrupt row for " + customerId, e);
            }
        }
    }
}

The output has three exceptions, each Caused by the next. Read it with the steps above: the last cause is NumberFormatException: For input string: "not-a-number", raised in Integer.parseInt. The first frame in your own code under it is CustomerRepository.find, line 28 or so, and that is where the investigation starts. The two outer messages tell you what the application was trying to do, and the inner one tells you what went wrong. A trace answers "what" at the bottom and "why it mattered" at the top.

Wrapping so the next reader can follow

How you write the catch decides how readable the trace will be. Three habits make traces useful:

java
// 1. Always pass the cause. A new exception without it throws away the real failure.
throw new IllegalStateException("Corrupt row for " + customerId, e);

// 2. Put the identifier in the message, and not the stack trace's job.
throw new CustomerNotFound("customer " + customerId + " not found in tenant " + tenant);

// 3. Do not log and rethrow. One failure should produce one trace.
catch (SQLException e) {
    throw new DataAccessFailure("load customer " + customerId, e);    // the caller logs it
}

A service that logs at every layer prints the same failure five times with five slightly different messages, and the on-call engineer cannot tell whether five things broke or one. Log at the boundary that decides what to do about the failure, and let everyone below it only wrap and throw.

Suppressed exceptions you can reproduce

The Suppressed: lines are easy to misread, so make one on purpose:

java
class Resource implements AutoCloseable {
    @Override
    public void close() {
        throw new IllegalStateException("close failed");
    }
}

try (Resource r = new Resource()) {
    throw new IllegalArgumentException("work failed");
}

The thrown exception is IllegalArgumentException: work failed, and Suppressed: java.lang.IllegalStateException: close failed hangs under it. Without try-with-resources, the close failure would have replaced the first exception, and the real cause would be gone. Read the main one first, as the cause, and treat the suppressed one as a second problem with the same resource.

Asynchronous code hides the caller

A trace from a CompletableFuture shows the pool thread, not the code that scheduled the work:

java
CompletableFuture<Order> order = CompletableFuture.supplyAsync(() -> repository.load(id), executor);
order.thenApply(this::price)
     .exceptionally(e -> {
         log.error("pricing failed for order {}", id, e);
         return null;
     });

The exception arrives wrapped in a CompletionException, and its cause is the real one, with frames that start at ForkJoinPool or your executor and never mention the controller that started it. Two habits help. Put the identifiers in the message, as above, since the stack cannot say which request this was. And capture the caller's stack when it is cheap to do so, so that an async failure can point back:

java
Throwable origin = new Throwable("scheduled from here");
executor.submit(() -> {
    try {
        work();
    } catch (RuntimeException e) {
        e.addSuppressed(origin);
        throw e;
    }
});

The origin throwable costs one stack capture per submission, which is fine for coarse tasks and too much for a hot path. Use it on the operations where "who started this" matters.

Getting the trace as data

When a trace has to cross a boundary, as a log field or an API response for operators, take it as a string, not by calling printStackTrace, which writes to standard error:

java
static String traceOf(Throwable t) {
    StringWriter out = new StringWriter();
    t.printStackTrace(new PrintWriter(out));
    return out.toString();
}

For structured logs, the logging library has a better answer: pass the exception as the last argument and let the JSON encoder write error.type, error.message and error.stack_trace fields. That keeps one trace in one searchable field, and not forty log lines that arrive out of order from different threads. Never return a trace to the caller of a public API; the problem-details format has room for a correlation id that lets you find the trace in the log without showing it to the world.

Where this does not apply

Asynchronous code (CompletableFuture, reactive pipelines) shows frames from the executor, not from the code that created the task; add context to the exception message or use Reactor's debug hooks. Virtual-thread traces look the same as platform ones. The [Throwable documentation](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html) describes the format, including the "... n more" rule. The format of each line is defined in the [StackTraceElement documentation](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/StackTraceElement.html), and the habit of reading from the bottom Caused by is the one most worth building.

Also inJava Core
Taggedhow to
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.