Scrivio Interview library
InternalsIntermediate6 min read · updated 12 November 2026

What does filling in a stack trace cost, how does StackWalker differ from Thread.getStackTrace, and when would you create an exception with writableStackTrace=false?

Creating an exception is expensive mainly because Throwable's constructor calls fillInStackTrace(), which walks the whole call stack and records every frame. StackWalker, added in Java 9, walks the stack lazily as a stream, so we can stop after a few frames, filter them and get Class objects, which is much cheaper than Thread.getStackTrace() building a full array. The protected Throwable constructor with writableStackTrace=false skips the trace entirely, which suits exceptions used as cheap, well-understood signals, at the cost of harder debugging.

Why this question is asked

Most of the time the cost of an exception does not matter, because exceptions are rare. It starts to matter when a service throws thousands of them per second as part of normal control flow, for example for validation failures or cache misses, and a profiler shows fillInStackTrace near the top. Interviewers ask this to see whether we understand where the cost comes from and the tools the JDK offers around it. In this answer, we will see what filling in a stack trace does, measure why it is costly, compare StackWalker with Thread.getStackTrace(), create traceless exceptions, and look at the JVM's own optimisation for hot built-in exceptions.

1What Filling In a Stack Trace Does

Every Throwable records where it was created. Its constructor calls fillInStackTrace(), a native method that walks the current thread's stack and saves a compact record of every frame. Later, when someone calls getStackTrace() or prints the exception, the JVM turns that record into StackTraceElement objects with class names, method names, file names and line numbers.

The walk itself is the expensive part, and it grows with stack depth. A Spring web request often runs 100 to 200 frames deep, through filters, interceptors, proxies and our own code, so every exception thrown there captures all of them, even if nobody ever looks at the trace.

Java
// Rough shape of a micro-benchmark (use JMH for real numbers)
new RuntimeException("x"); // walks and records the full stack
new RuntimeException("x", null, false, false) {}; // no stack walk; anonymous subclass, since the constructor is protected
// typically the first is many times slower at depth 100+; check on your own JVM

Notice that the throw statement itself is cheap. It is creating the exception object that costs, because that is when the trace is captured. Throwing a preallocated exception skips the cost, but then the trace shows where it was created, not where it was thrown.

2StackWalker Versus Thread.getStackTrace()

Sometimes we want stack information without an exception, for example to find the calling class for logging or security checks. The old way was Thread.currentThread().getStackTrace() or new Throwable().getStackTrace(). Both capture the entire stack and build an array of StackTraceElement objects, one per frame, with strings for every name, even when we only need the second frame.

StackWalker, in java.lang since Java 9, is lazy. We give it a function that receives a Stream of StackFrame objects, and frames are only materialised as the stream pulls them. If we stop after three frames, the JVM only walks three frames. With the RETAIN_CLASS_REFERENCE option we can also get the actual Class object of each frame, which getStackTrace() never offers, since it only gives class names as strings.

Java
StackWalker walker = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);
Class<?> caller = walker.getCallerClass(); // the class that called our method
List<String> top3 = walker.walk(frames -> frames
.filter(f -> f.getClassName().startsWith("com.acme")) // skip framework frames
.limit(3) // stop walking early
.map(f -> f.getMethodName() + ":" + f.getLineNumber())
.toList()); // e.g. [load:57, get:31, handle:88]
StackTraceElement[] all = Thread.currentThread().getStackTrace(); // always the whole stack
Thread.getStackTrace() and StackWalker
Thread.getStackTrace()StackWalker (Java 9+)
WalkEager, whole stackLazy, as the stream pulls frames
Stop earlyNoYes, with limit or takeWhile
Filter framesAfterwards, on the full arrayWhile walking
Class objectsNo, only class name stringsYes, with RETAIN_CLASS_REFERENCE
ThreadAny threadCurrent thread only

So StackWalker is cheaper when we need part of the stack, and more capable because of filtering and Class references. When we really need every frame, the difference is smaller.

3Exceptions Without a Stack Trace

Throwable has a protected constructor with two extra flags: Throwable(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace). Exception and RuntimeException expose the same protected constructor to subclasses. When writableStackTrace is false, the constructor does not call fillInStackTrace(), and getStackTrace() returns an empty array.

Java
public final class RateLimitedException extends RuntimeException {
public RateLimitedException(String clientId) {
super("rate limited: " + clientId, null, false, false); // no suppression list, no stack trace
}
}
RateLimitedException e = new RateLimitedException("c-17");
System.out.println(e.getStackTrace().length); // 0

This is the right tool for an exception used as a cheap signal on a well-understood path: thrown often, always caught by known code, and never needed for debugging because the message and type say everything. Before Java 7 the same effect was achieved by overriding fillInStackTrace() to return this, which we still see in older libraries.

4The JVM's Own Shortcut: OmitStackTraceInFastThrow

The HotSpot JIT has a related optimisation. When compiled code throws certain built-in exceptions, such as NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException or ClassCastException, very often from the same place, the JIT may replace them with a preallocated exception that has no stack trace. This is controlled by the flag OmitStackTraceInFastThrow, which is on by default.

The surprise comes in production logs: after the first few occurrences, the same NullPointerException starts appearing with a message and no stack trace at all, and engineers cannot find where it came from. The fix for debugging is to scroll back to the earliest occurrences, which still have full traces, or to run with -XX:-OmitStackTraceInFastThrow, which turns the optimisation off.

Step throughHow a hot NullPointerException loses its trace
  1. Code throws NPE at the same placeinterpreted or first compiled runs
  2. Full stack trace loggedearly occurrences
  3. Thrown very often from compiled code?
    YesJIT reuses a preallocated NPENoKeep creating full exceptions
  4. Logs show NPE with no traceunless -XX:-OmitStackTraceInFastThrow

4 steps in order. Play them, or step through them one at a time.

5The Trade-Off: Speed Versus Debuggability

A traceless exception is cheaper, but when something unexpected happens it gives us almost nothing to go on. So we use writableStackTrace=false only for exceptions whose meaning is complete without a trace, on paths we understand well, and never for errors that signal bugs. Often the better fix is not to throw at all on a hot path: return an Optional, a result object, or a boolean, and keep exceptions for exceptional cases.

6Follow-up questions

Is it safe to reuse one static exception instance?

It works for traceless signals, and some high-performance libraries do it, but a shared instance must be immutable: no suppression list (enableSuppression false), no cause set later, and no trace. Otherwise one thread's addSuppressed or initCause would leak into every other use.

Does enableSuppression matter for performance?

Only slightly. Suppressed exceptions are the ones try-with-resources attaches when closing a resource also fails. Disabling it just means addSuppressed is ignored, which is appropriate for a cheap signal exception but would hide information in normal error handling.

Why is getStackTrace() slower than fillInStackTrace()?

fillInStackTrace() records a compact internal form. getStackTrace() then has to decode it into StackTraceElement objects, resolving method names, file names and line numbers as strings. That is why logging a trace costs more than creating the exception.

7Conclusion

In this answer, we saw that most of an exception's cost comes from fillInStackTrace(), called by Throwable's constructor to walk and record the stack. StackWalker walks lazily as a stream, so it can stop early, filter frames and return Class objects, which makes it cheaper than Thread.getStackTrace() when we need only part of the stack. The protected constructor with writableStackTrace=false creates exceptions with no trace for cheap, well-understood signals. We also met OmitStackTraceInFastThrow, which drops traces of hot built-in exceptions unless disabled with -XX:-OmitStackTraceInFastThrow, and we kept in mind that traceless exceptions make debugging harder.

What to say in the interviewAbout 80 seconds aloud

Open with

Most of the cost of an exception is not the throw, it is the construction. Throwable's constructor calls fillInStackTrace, which walks the entire thread stack and records every frame, so in a Spring request that is 150 frames deep, every exception captures 150 frames even if nobody reads them.

Then, if they want more

Turning that into StackTraceElement objects when we print it costs even more. StackWalker, since Java 9, is the modern way to inspect the stack.

It is lazy: I pass a function that gets a stream of frames, and the JVM only walks as far as the stream pulls, so I can filter to my own packages and limit to three frames. With RETAIN_CLASS_REFERENCE it also gives me the actual Class objects, for example with getCallerClass. Thread.getStackTrace always builds the full array of strings.

For exceptions used as cheap signals, like a rate-limit signal thrown thousands of times a second and always caught, I would use the protected constructor with writableStackTrace false, which skips fillInStackTrace entirely. Related to this, HotSpot's OmitStackTraceInFastThrow makes hot built-in exceptions like NullPointerException lose their traces after a while, and -XX:-OmitStackTraceInFastThrow turns that off.

The trade-off is debuggability, so I only drop traces where the type and message say everything.

About this answer

Last updated
12 November 2026
Versions it names
Java 9, Java 7
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What does filling in a stack trace cost, how does StackWalker differ from...": https://scrivio-interview-library.netlify.app/java/exceptions/7cfaa10f3e/