Skip to content
Tutorials Center
My learning

Topics

Lesson 77 of 201 ยท Exceptions

Stack Traces and Exception Chaining

Read Java stack traces line by line, chain exceptions with a cause, handle suppressed exceptions, use StackWalker and learn what each Caused by and "... n more" line really means.

When a Java program fails, the most valuable thing it gives you is the stack trace: a list of the method calls that were active at the moment the exception was created. Beginners often see it as a wall of red noise. Experienced developers read it in five seconds and know which line to open. You already saw the basics in Debugging Java Programs; this lesson goes deeper into how traces are built, how to read the ones with Caused by: and Suppressed: sections, how to inspect them from code, and how to chain exceptions so that a high-level error keeps the story of the low-level one that started it.

Everything here runs on this site's runner. One thing to know first: programs on this page are started by the Java source launcher, so the bottom five lines of every trace belong to the launcher (jdk.compiler/...). On your own computer after javac and java, those lines won't be there.

What is in a stack trace

Each running thread has a call stack: a frame is added when a method is called and removed when it returns. When you create an exception, the JVM records a snapshot of that stack in the exception object. This happens at the moment of new, not at throw. Printing the exception shows the snapshot, newest call first.

flowchart TB
    subgraph Stack["Call stack when the exception is created"]
        direction TB
        F3["level3 (Main.java:3)<br/>data[5] fails here"]
        F2["level2 (Main.java:7)"]
        F1["level1 (Main.java:11)"]
        F0["main (Main.java:16)"]
    end
    F3 --> F2 --> F1 --> F0

The top frame is where the exception was created; each frame below it is the caller that led there.

Java Reading a stack trace

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Read the output from the top:

  1. The first line is exception class: message. The class says what kind of problem it is; the message gives details (here, Index 5 out of bounds for length 3).
  2. Each at line is one frame in the format at package.Class.method(File.java:line). The first one (Main.level3, line 3) is where the exception was created, so it is the place where things went wrong.
  3. Going down you see who called whom: level2 called level3, level1 called level2, and main called level1. That is the path your program took to get there.
  4. The last five lines start with java.base/ or jdk.compiler/. They are JDK internals that launched main. Frames from libraries are marked with the module name before the slash.

A good habit: find the first line that belongs to your own code. If the top frames are JDK code (for example inside Integer.parseInt), the bug is usually in how your code called the JDK, so keep going down until you reach your own method.

If a source file was compiled without debug information, or a method is native, you see (Unknown Source) or (Native Method) instead of a line number. Lambdas show up as synthetic names like lambda$main$0.

Looking at a trace from code

An exception is an object, so you can inspect its trace in code instead of printing it:

  • getStackTrace() returns a StackTraceElement[], newest first. Each element has getClassName(), getMethodName(), getFileName() and getLineNumber().
  • printStackTrace() prints to System.err; printStackTrace(System.out) or printStackTrace(PrintWriter) send it elsewhere. To get the trace as a String (for a log message), print into a StringWriter.
  • Thread.currentThread().getStackTrace() and Thread.dumpStack() show the current stack without any exception.

The modern API for walking the stack is StackWalker (Java 9). It is lazy and efficient: you can stop after a few frames instead of building the whole trace, and you can filter. Asking for the caller's class is the usual reason to use it.

Java StackWalker and a trace as a string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice that StackWalker starts at the method that calls it (c), while new Exception() records the line where it was created. The walker's stream lets you write things like "give me the first frame that is not in my logging library", something that used to require building and scanning an entire Throwable.

Exception chaining: keeping the cause

In a layered program, low-level exceptions mean nothing to the layer above. A SQLException is no use to a controller that wants to show "could not save order". The standard answer is to wrap: catch the low-level exception, throw a new, higher-level one, and pass the original as its cause. The result is a chain, and the trace prints each link under a Caused by: heading.

flowchart LR
    A["NumberFormatException<br/>For input string 12x"] -->|"is the cause of"| B["DataAccessException<br/>cannot load settings"]
    B -->|"is the cause of"| C["Caught at the top level<br/>log the whole chain"]

Each wrapper keeps a reference to what it wrapped, so no information is lost on the way up.

Java A chain with Caused by

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The trace has two blocks. The first is the exception you caught, cannot load settings, thrown at Main.load (line 16). The second begins at Caused by: and shows the original NumberFormatException, with its own frames, down into Integer.parseInt and Main.readConfig. The cause is where you should start debugging: it is what actually went wrong.

What does "... 6 more" mean?

The two traces overlap. After Main.load(Main.java:14) the cause's trace continues with Main.main and the five launcher frames, which are identical to the frames at the bottom of the wrapper's trace. To avoid printing them twice, Java stops and writes ... 6 more to say "the remaining 6 frames are the same as the enclosing trace". It is not an error and nothing is hidden: the frames are the common tail.

Creating and reading a chain

There are four ways to attach a cause:

  • Constructor with a cause: new DataAccessException("message", cause). This is the normal way. All the standard exceptions have such constructors: RuntimeException(String, Throwable), IllegalStateException(String, Throwable), IOException(String, Throwable), and so on.
  • Constructor with only a cause: new RuntimeException(cause) copies the cause's toString() as the message.
  • initCause(cause) for old exception classes that have no cause constructor. It can be called once, and only if no cause was set before; a second call throws IllegalStateException.
  • getCause() reads it, returning null at the end of the chain.

To find the original problem, follow getCause() until it returns null, as the loop above does. Be careful with that loop in code that handles exceptions from unknown libraries: a buggy exception could point to itself and create a cycle, which Java's own printer guards against with a [CIRCULAR REFERENCE: ...] marker.

Java Cause constructors and initCause

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

You can see three things here. new RuntimeException(inner) builds its message from the cause (java.lang.IllegalStateException: x), while the two-argument version keeps your own message. A second initCause call is refused. And setStackTrace can replace a trace with anything you like (it is meant for frameworks that rebuild traces, for example after sending an exception over the network).

Chaining rules that save hours

  1. Never swallow the cause. catch (SQLException e) { throw new ServiceException("save failed"); } throws away the one fact that explains the failure. Always pass e.
  2. Wrap at layer boundaries, not at every method. Each layer should throw exceptions that make sense in its own vocabulary (see Exception Best Practices and Custom Exceptions).
  3. Log or rethrow, not both. If you log and rethrow, the same trace appears several times as the exception travels up. Wrap and throw in the lower layers; log once where the error is finally handled.
  4. Put useful data in the message, such as the id or file name involved. The trace says where, the message says which one.
  5. Log the whole exception object (logger.error("msg", e)), not e.getMessage() only, or you lose the trace and the whole chain.

Suppressed exceptions

Chaining records why an exception happened. A second mechanism records other exceptions that occurred at the same time and would otherwise be lost. This happens most often with try-with-resources: if the body throws and then closing a resource throws as well, Java keeps the first exception as the main one and attaches the second as suppressed.

Java Suppressed exceptions from close()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The main exception is work failed. Under it, indented one level, come two Suppressed: blocks, one for each resource whose close() failed, in the order they were closed (B first, then A, because resources close in reverse order). You read them with getSuppressed(), which returns an array, and you can add your own with addSuppressed(Throwable), for example when a finally block might hide the original error. Without this mechanism, the exception from close() would replace the real one and you would debug the wrong problem.

Mechanism Answers the question Methods
Cause (Caused by:) "What lower-level failure led to this one?" getCause(), initCause()
Suppressed (Suppressed:) "What else went wrong while this was being handled?" getSuppressed(), addSuppressed()

The cost of a stack trace

Filling in a stack trace is not free. When an exception is created, the JVM walks the whole stack and copies it. In a deep stack (a web framework often has 50 to 200 frames) this takes microseconds, which adds up if you throw millions of exceptions. Two consequences:

  • Don't use exceptions for ordinary control flow, such as stopping a loop or returning "not found". Return an Optional or a special value instead (Optional).
  • Rarely, in performance-critical code, an exception class can switch the trace off with the four-argument protected constructor super(message, cause, enableSuppression, writableStackTrace); passing false for the last argument produces an exception with an empty trace (the Quiet class above shows quiet frames: 0). Do this only for internal, frequently thrown, always-caught exceptions, because the loss of the trace makes debugging impossible if one escapes.

Warning: A stack trace can contain sensitive information: file paths, class names, SQL, sometimes values in the message. Show users a short, friendly error and write the full trace to your server log. Never send stack traces to the browser of a public site.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where in a stack trace do you find the code line that created the exception?

    Frames are listed newest first, so the first 'at' line is where the exception object was created. The bottom lines show the callers.
  2. 2. What does the line '... 6 more' under a 'Caused by:' block mean?

    The cause's trace shares its tail with the wrapper's trace. Java prints the common frames only once and summarizes them.
  3. 3. What is wrong with 'catch (IOException e) { throw new ServiceException("load failed"); }'?

    Without the cause argument the chain is broken, and the trace no longer shows what really failed. Use new ServiceException("load failed", e).
  4. 4. A try-with-resources body throws A and then close() throws B. What does the caller receive?

    The exception from the body is the primary one; exceptions from closing are attached as suppressed so that nothing hides the original error.
  5. 5. Which call attaches a cause to an exception whose class has no cause constructor?

    initCause can be called once on an exception that has no cause yet. A second call throws IllegalStateException.

Summary

  • A stack trace is a snapshot of the call stack taken when the exception is created: the first at line is where, the lines below are who called whom.
  • Find the first frame in your own code; the first line of the trace tells you the type and message.
  • getStackTrace(), printStackTrace(PrintWriter) and StackWalker give code access to the trace; StackWalker is lazy and can filter.
  • Chain exceptions with the cause constructor or initCause; each Caused by: block is a lower-level exception, and ... n more marks frames shared with the enclosing trace.
  • Never drop the cause, wrap at layer boundaries, and log the full exception once.
  • Suppressed: blocks hold secondary exceptions, such as failures in close(), that would otherwise be lost.
  • Exceptions cost time to create because of the trace; don't use them for normal control flow, and never expose traces to end users.

Next: Wrapper Classes and Autoboxing, where primitives become objects and == on an Integer can surprise you.