Stack traces
suggest changeA stack trace is the list of method calls that were active at a given moment. The JVM records one every time a Throwable is created, and prints it when an exception is not caught. Being able to read stack traces quickly, and to get them out of your program in the right form, is one of the most useful debugging skills in Java.
This article covers the format of a modern stack trace (including chained and suppressed exceptions), how to access stack frames from code with getStackTrace() and StackWalker, and the performance and JVM details that sometimes make a trace look wrong or go missing. For a gentler introduction see Creating and reading stacktraces; for debuggers and thread dumps see Debugging.
Anatomy of a stack trace
public class Orders {
public static void main(String[] args) {
new Orders().checkout(0);
}
void checkout(int items) {
System.out.println(average(100, items));
}
int average(int total, int count) {
return total / count;
}
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Orders.average(Orders.java:11)
at Orders.checkout(Orders.java:7)
at Orders.main(Orders.java:3)
Exception in thread "main"is printed by the default uncaught exception handler and names the thread that diedjava.lang.ArithmeticException: / by zerois the exception'stoString(): fully qualified class name, thengetMessage()- each
atline is a frame:class.method(file:line) - the top frame is where the exception was created; each frame below is the caller of the one above it
So read from the top: line 11 failed, it was called from line 7, which was called from line 3.
Frame formats you will see
Since Java 9, frames from classes in named modules are prefixed with the module name. Frames inside the JDK therefore look different from frames in your code:
public class Parse {
public static void main(String[] args) {
int n = Integer.parseInt("abc");
}
}
Exception in thread "main" java.lang.NumberFormatException: For input string: "abc"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:565)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at Parse.main(Parse.java:3)
Line numbers inside JDK classes vary between JDK versions. The general format of a frame is [classloader/][module@version/]class.method(source), with parts omitted when they don't apply. Common variations:
| Frame | Meaning |
|---|---|
at java.base/java.util.Objects.requireNonNull(Objects.java:220) |
class in JDK module java.base |
at com.example.app@1.2/com.example.Main.run(Main.java:10) |
class in your named module com.example.app version 1.2 |
at Orders.main(Orders.java:3) |
class on the classpath (unnamed module) |
at Outer$Inner.run(Outer.java:20) |
nested class Inner inside Outer |
at Outer$1.run(Outer.java:25) |
first anonymous class in Outer |
at Point.<init>(Point.java:5) |
constructor or instance initializer |
at Config.<clinit>(Config.java:3) |
static initializer or static field initializer |
at Main.lambda$main$0(Main.java:8) |
body of a lambda defined in main |
at java.base/jdk.internal.misc.Unsafe.park(Native Method) |
native method, no line number |
at Foo.bar(Unknown Source) |
class compiled without debug info |
Lambdas
A lambda body is compiled into a private synthetic method named lambda$<enclosing method>$<n>:
public class Lambda {
public static void main(String[] args) {
Runnable r = () -> {
throw new IllegalStateException("boom");
};
r.run();
}
}
Exception in thread "main" java.lang.IllegalStateException: boom
at Lambda.lambda$main$0(Lambda.java:4)
at Lambda.main(Lambda.java:6)
The JVM also generates a hidden class that implements Runnable and forwards run() to lambda$main$0. Its frame is hidden from stack traces by default; run with -XX:+UnlockDiagnosticVMOptions -XX:+ShowHiddenFrames to see it (rarely useful outside JVM debugging).
Stream pipelines produce long traces full of java.util.stream frames. Skip them and look for the lambda$... frame in your class, and the frame for the terminal operation (toList, forEach, collect) in your code.
Missing line numbers
javac stores the source file name and line numbers in class files by default. You see Unknown Source when the code was compiled with -g:none or post-processed by a tool that strips debug info. Code shrunk and obfuscated by ProGuard or R8 has renamed classes and methods; use the mapping file and the retrace tool to translate the trace back.
Chained exceptions: Caused by
When code catches an exception and throws a new one, it should pass the original as the cause. The cause is printed after the main trace:
import java.io.IOException;
import java.io.UncheckedIOException;
public class Config {
public static void main(String[] args) {
load("app.conf");
}
static void load(String name) {
try {
readFile(name);
} catch (IOException e) {
throw new UncheckedIOException("cannot load " + name, e);
}
}
static void readFile(String name) throws IOException {
throw new IOException("permission denied");
}
}
Exception in thread "main" java.io.UncheckedIOException: cannot load app.conf
at Config.load(Config.java:13)
at Config.main(Config.java:6)
Caused by: java.io.IOException: permission denied
at Config.readFile(Config.java:18)
at Config.load(Config.java:11)
... 1 more
... 1 more means the last frame of the cause's trace (Config.main(Config.java:6)) is identical to the last frame of the trace above, so it is not repeated. In a real application with framework code, this saves dozens of lines.
In long chains, the last Caused by: is usually the root cause and the most informative. The outer exceptions add context (which file, which request).
If you throw a new exception without the cause, the original trace is lost:
} catch (IOException e) {
throw new RuntimeException("cannot load " + name); // bad: cause discarded
// throw new RuntimeException("cannot load " + name, e); // good
}
If an exception class has no constructor taking a cause, use initCause():
var ex = new IllegalStateException("cannot load " + name);
ex.initCause(e);
throw ex;
Suppressed exceptions
try-with-resources closes resources even when the body throws. If close() also throws, that second exception is attached to the first as a suppressed exception instead of replacing it:
public class Cleanup {
static class Res implements AutoCloseable {
public void close() {
throw new IllegalStateException("close failed");
}
}
public static void main(String[] args) {
try (Res r = new Res()) { throw new IllegalStateException("body failed"); }
}
}
Exception in thread "main" java.lang.IllegalStateException: body failed
at Cleanup.main(Cleanup.java:9)
Suppressed: java.lang.IllegalStateException: close failed
at Cleanup$Res.close(Cleanup.java:4)
... 1 more
Suppressed exceptions are indented with a tab. They can have their own Caused by: sections, which are indented too. From code, get them with getSuppressed(), and add your own with addSuppressed():
for (Throwable s : ex.getSuppressed()) {
System.err.println("suppressed: " + s);
}
Accessing stack frames from code
Throwable.getStackTrace() returns the recorded frames as an array of StackTraceElement, top frame first:
public class Frames {
public static void main(String[] args) {
try {
step1();
} catch (RuntimeException e) {
for (StackTraceElement f : e.getStackTrace()) {
System.out.printf("%s.%s (%s line %d)%n",
f.getClassName(), f.getMethodName(),
f.getFileName(), f.getLineNumber());
}
}
}
static void step1() { step2(); }
static void step2() { throw new RuntimeException("failed"); }
}
Frames.step2 (Frames.java line 16)
Frames.step1 (Frames.java line 14)
Frames.main (Frames.java line 4)
StackTraceElement also has getModuleName(), getModuleVersion(), getClassLoaderName() and isNativeMethod(). getLineNumber() returns a negative number when the line is unknown (-2 for native methods), and getFileName() can return null.
Prefer these methods to parsing the text output of printStackTrace().
Finding the root cause
static Throwable rootCause(Throwable t) {
Throwable cur = t;
while (cur.getCause() != null) {
cur = cur.getCause();
}
return cur;
}
getCause() returns null rather than the exception itself when there is no cause, so this loop terminates for normally built chains. Apache Commons Lang (ExceptionUtils.getRootCause) and Guava (Throwables.getRootCause) provide versions that also detect cycles.
Stack trace as a String
To store a trace in a database, send it in an error report or show it in a UI, print it into a StringWriter:
import java.io.PrintWriter;
import java.io.StringWriter;
static String stackTraceToString(Throwable t) {
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
return sw.toString();
}
The result includes all Caused by: and Suppressed: sections, exactly as printed to the console.
Stack trace of the current thread
You don't need an exception to get a stack trace. There are three ways to find out how the current code was reached:
public class Who {
public static void main(String[] args) {
audit();
}
static void audit() {
// 1. print to System.err; useful for quick "who calls this?" debugging
Thread.dumpStack();
// 2. get frames from a Throwable that is never thrown
StackTraceElement[] frames = new Throwable().getStackTrace();
System.out.println(frames[0].getMethodName()); // audit
System.out.println(frames[1].getMethodName()); // main
// 3. Thread.getStackTrace(); for the current thread, frame 0 is
// java.lang.Thread.getStackTrace itself
StackTraceElement[] t = Thread.currentThread().getStackTrace();
System.out.println(t[1].getMethodName()); // audit
}
}
java.lang.Exception: Stack trace
at java.base/java.lang.Thread.dumpStack(Thread.java:2018)
at Who.audit(Who.java:8)
at Who.main(Who.java:3)
audit
main
audit
Thread.dumpStack() is a convenience for new Exception("Stack trace").printStackTrace(). It writes to System.err, so its output may interleave with System.out in a different order than shown.
To capture the stacks of all threads, for example from a watchdog that detects a hang, use Thread.getAllStackTraces():
for (var entry : Thread.getAllStackTraces().entrySet()) {
Thread th = entry.getKey();
System.out.println(th.getName() + " (" + th.getState() + ")");
for (StackTraceElement f : entry.getValue()) {
System.out.println(" at " + f);
}
}
From outside the process, jcmd <pid> Thread.print or jstack <pid> prints the same information plus lock details; see Debugging.
StackWalker
Thread.getStackTrace() and Throwable.getStackTrace() capture the whole stack eagerly, which is wasteful when you need only the top few frames. java.lang.StackWalker (Java 9+) walks the stack lazily as a Stream and can give you Class objects, not just names. See also Stack-Walking API.
import java.util.List;
public class Walk {
public static void main(String[] args) {
a();
}
static void a() { b(); }
static void b() {
// frames start at the method that calls walk()/forEach(), here b()
StackWalker.getInstance().forEach(f ->
System.out.println(f.getMethodName() + ":" + f.getLineNumber()));
List<String> top2 = StackWalker.getInstance().walk(frames -> frames
.limit(2)
.map(StackWalker.StackFrame::getMethodName)
.toList());
System.out.println(top2);
}
}
b:12
a:8
main:5
[b, a]
Only the frames consumed by the stream are materialized, so limit(2) is cheap even with a deep stack.
Who called me?
A common use is reporting the caller's location, for example in a tiny logging helper:
public class Log {
static void log(String msg) {
StackWalker.StackFrame caller = StackWalker.getInstance()
.walk(frames -> frames.skip(1).findFirst()) // skip log() itself
.orElseThrow();
System.out.printf("[%s.%s:%d] %s%n", caller.getClassName(),
caller.getMethodName(), caller.getLineNumber(), msg);
}
public static void main(String[] args) {
log("starting");
}
}
[Log.main:11] starting
To get the caller's Class (for example to load a resource relative to it), use getCallerClass(), which requires the RETAIN_CLASS_REFERENCE option:
private static final StackWalker WALKER =
StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);
static void register() {
Class<?> caller = WALKER.getCallerClass(); // class of the method that called register()
System.out.println("registered by " + caller.getName());
}
Other options are SHOW_REFLECT_FRAMES (include Method.invoke and reflection frames) and SHOW_HIDDEN_FRAMES (also include hidden frames such as lambda proxy classes).
Logging stack traces
In application code, don't call printStackTrace(); it goes to System.err, bypasses your log configuration and has no timestamp. Pass the exception object to the logger as the last argument, and it prints the full trace with causes:
// SLF4J / Logback / Log4j 2
log.error("failed to process order {}", orderId, e);
// java.util.logging
logger.log(Level.SEVERE, "failed to process order " + orderId, e);
A frequent mistake is logging only the message, which throws away the trace and often prints just null:
log.error(e.getMessage()); // bad: no trace, no exception type
log.error("failed: " + e); // bad: type and message only
Also avoid logging the same exception at every layer while rethrowing it; log it once where it is handled. See Pitfall: Excessive or inappropriate stacktraces.
For exceptions nobody catches, a default handler ensures they reach your log instead of only the console:
Thread.setDefaultUncaughtExceptionHandler((thread, ex) ->
log.error("uncaught exception in thread {}", thread.getName(), ex));
When the stack trace is missing or truncated
The JIT drops traces of hot exceptions
If a NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException, ArrayStoreException or ClassCastException is thrown implicitly by the JVM many times from the same place in compiled code, HotSpot starts throwing a preallocated exception with no message and no stack trace. Logs then show something like:
java.lang.NullPointerException
with nothing below it. The full trace was printed the first few times, so search older logs. To disable the optimization, start the JVM with:
java -XX:-OmitStackTraceInFastThrow -jar app.jar
Deep recursion
A StackOverflowError trace is cut after 1024 frames (the -XX:MaxJavaStackTraceDepth default), so you typically see the same few recursive frames repeated and never reach main. Look for the repeating pattern; it tells you which methods recurse. The limit can be raised with -XX:MaxJavaStackTraceDepth=10000.
The exception was created elsewhere
The stack trace is recorded when the exception is created, not when it is thrown. An exception stored in a field and thrown later shows where it was constructed. Exceptions rethrown from another thread show the other thread's stack: for example ExecutionException from Future.get() wraps the task's exception, and the cause's frames are from the pool thread.
Performance: exceptions without stack traces
Capturing the stack (fillInStackTrace(), called by the Throwable constructor) is the most expensive part of creating an exception, and its cost grows with stack depth. For exceptions used for control flow in hot paths, where the trace is never looked at, you can disable it with the protected four-argument constructor:
public class ValidationException extends RuntimeException {
public ValidationException(String message) {
// message, cause, enableSuppression, writableStackTrace
super(message, null, false, false);
}
}
var e = new ValidationException("age must be positive");
System.out.println(e.getStackTrace().length);
e.printStackTrace();
0
ValidationException: age must be positive
Use this only when you are sure nobody needs to know where the exception came from. For ordinary error handling, the cost of a stack trace is negligible compared to its debugging value.
You can also replace the recorded frames with setStackTrace(). This is mostly used by frameworks (for example to remove internal proxy frames) and in tests; regular code rarely needs it.
Summary
- read a trace from the top down; find the first frame in your code, then read every
Caused by:andSuppressed:section - always pass the original exception as the cause when wrapping it
- use
getStackTrace()andgetCause()to inspect traces from code; useStackWalkerwhen you need only a few frames of the current thread - log exceptions by passing the exception object to the logger, not
e.getMessage() - a trace with no frames may come from
OmitStackTraceInFastThrow; a trace that never reachesmainis usually a truncatedStackOverflowError