What does constructing a Java Throwable cost, what does writableStackTrace turn off, and when is reusing a stackless exception justified?
answer
- paid at new, not at throw
- two stages: capture, then first read
- depth matters, up to a flag's cap
- the protected four-argument constructor
- shared signal holds no per-throw state
basics
~20 sConstructing a Java Throwable mostly costs fillInStackTrace walking the thread's frames, so it grows with stack depth. Passing writableStackTrace=false skips that walk and leaves no trace. A shared stackless instance suits only a measured, hot control-flow signal nobody diagnoses.
solid answer
~40 sEvery public `Throwable` constructor calls `fillInStackTrace()`, whose private native half walks the current thread's frames into a compact `backtrace`, so the cost grows with depth up to HotSpot's `MaxJavaStackTraceDepth`, 1024 by default at Java 27 and 25. `StackTraceElement` objects are built only on first read, as through `getStackTrace()` or `printStackTrace()`. The protected four-argument constructor with `writableStackTrace=false` skips the walk and writes `null` to the private `stackTrace` field: later `fillInStackTrace()` calls do nothing, `setStackTrace` only validates its argument, and `getStackTrace()` returns an empty array. Reusing one instance is justified only when a profile shows the throw site matters, a return value will not do, the signal is caught nearby and never logged, and it carries no per-throw data; then pass a `null` cause and `enableSuppression=false` as well, so nothing accumulates on the shared object.
code
java · 34 linespublic class SignalDemo {
static final class ParseBacktrack extends RuntimeException {
static final ParseBacktrack INSTANCE = new ParseBacktrack();
private ParseBacktrack() {
super("parse backtrack", null, false, false);
}
}
static boolean tryParse(String input) {
try {
parse(input, 0);
return true;
} catch (ParseBacktrack signal) {
return false;
}
}
static void parse(String input, int position) {
if (position == input.length()) {
return;
}
if (input.charAt(position) == '!') {
throw ParseBacktrack.INSTANCE;
}
parse(input, position + 1);
}
public static void main(String[] args) {
System.out.println(tryParse("abc")); // true
System.out.println(tryParse("a!c")); // false
System.out.println(ParseBacktrack.INSTANCE.getStackTrace().length); // 0
}
}go deeper
Recall that creating an exception records the call stack, and that this recording, not the object itself, is what makes a new exception expensive. Name the method that does it: fillInStackTrace.
Explain the two stages: fillInStackTrace captures a compact backtrace at construction, and StackTraceElement objects appear only on first read. Then say what the protected constructor's writableStackTrace=false changes.
Show the production judgment: a profile first, and a shared stackless signal only where nobody reads the trace. Recognise fast-throw NullPointerExceptions with no frames in logs, and know -XX:-OmitStackTraceInFastThrow.
Weigh lost diagnosability against saved cycles as a team default: refuse stackless exceptions for anything that can reach a log, and prefer a return-value design when a path is expected and hot.
## What constructing one does A `Throwable` is the root of everything Java can throw. Creating one allocates an ordinary object and then does something ordinary objects do not: it records the calling thread's stack. All four public constructors call `fillInStackTrace()` unconditionally, so the cost is paid whether or not anyone reads the trace, and unless code calls that method again, the trace describes where the exception was **constructed**, not where it was later thrown. The work happens in two stages, and treating them as one is the common mistake: 1. **Capture, during construction.** `fillInStackTrace()` calls a private native overload. In HotSpot, `java_lang_Throwable::fill_in_stack_trace` loops over the thread's frames, skips `fillInStackTrace` and the exception's own `<init>` frames, and appends each frame's method and bytecode index to a compact structure held in the private transient fields `backtrace` and `depth`. 2. **Materialisation, on first read.** The private `getOurStackTrace()` converts that structure into a `StackTraceElement[]` through `StackTraceElement.of(backtrace, depth)` and caches the array. `getStackTrace()`, `printStackTrace()` and serialization all go through it. ## What it costs - **Capture grows with depth.** There is one entry per visible frame, inlined frames included, up to `MaxJavaStackTraceDepth`, a HotSpot product flag that defaults to 1024 (0 means no limit). At 5,000 frames of recursion, the trace holds exactly 1,024 elements. - **Materialisation is a separate bill.** Timed once on one machine on OpenJDK 27.0.1 without JMH, capture, with the recursion to reach that depth counted in, went from about 0.2 microseconds on a shallow stack to about 15 at 1,000 frames, and the first `getStackTrace()` at that depth took about five times as long. Read those as a shape, not as figures to quote. - **The throw is a separate cost, and inlining decides it.** Construction does not find a handler. In the JVMS model, the JVM searches the current method's exception handlers and, when none matches, pops the frame and rethrows in the caller. C2 can compile a throw inlined into the frame that catches it to a direct branch. Timed once on OpenJDK 27.0.1 without JMH, a shared stackless instance caught one frame up cost about the same as a sentinel return when inlined, and roughly 55 ns a throw with inlining disabled. ## What `writableStackTrace` turns off `Throwable` has a protected four-argument constructor, `(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace)`, since Java 7. `Exception`, `RuntimeException` and `Error` each have a protected one that delegates to it, so only a subclass can call it. The body of `Throwable`'s starts: ```java if (writableStackTrace) { fillInStackTrace(); } else { stackTrace = null; } ``` A `null` in the private `stackTrace` field means no further writes. `fillInStackTrace()` then has no effect, `setStackTrace` validates its argument and stores nothing, and `getStackTrace()` returns a zero-length array. Overriding `fillInStackTrace()` is the other way to skip the walk, and a later `setStackTrace` behaves differently: | Approach | Walks the stack | `getStackTrace()` | Later `setStackTrace` | |---|---|---|---| | Public constructor | Yes | Captured frames | Replaces the trace | | `writableStackTrace=false` | No | Empty | Validates only | | Override returning `this` | No | Empty | Replaces the trace | ## When reusing one is justified The `Throwable` documentation names the case: an exception object "repeatedly caught and rethrown, such as to implement control flow between two sub-systems" is a situation where immutable throwables "would be appropriate". It also says disabling suppression should occur only in exceptional circumstances. So treat a shared instance as an exception to the rule, and ask for all of these: - **A profile shows it matters.** The throw site is hot enough for capture or allocation to appear, and a return value, the first choice for an expected outcome, will not fit. - **The catch is close and certain.** The signal is caught inside the same subsystem and never reaches a log, where a frameless exception tells nobody where it came from. - **It carries no per-throw data.** A shared instance has a fixed message, because anything request-specific would be visible to every thread that catches it. - **Suppression is off.** With it on, each `addSuppressed` appends to one shared list that never shrinks. With `enableSuppression=false`, `addSuppressed` records nothing. - **The cause is closed.** The four-argument constructor stores the cause it is given, `null` included, so a later `initCause` throws `IllegalStateException`. A new stackless instance per throw is the lighter step: it saves the walk, keeps per-throw data, and still constructs an object each time. Do not cache an exception that has a trace: every later throw would report the place it was first constructed. ## The JVM does this on its own HotSpot's `OmitStackTraceInFastThrow` defaults to true. C2 treats a throw as hot when its site keeps throwing, and also, in a method with a local handler, once any site there has already thrown the same way. A hot throw can use a preallocated instance of `NullPointerException`, `ArithmeticException`, `ArrayIndexOutOfBoundsException`, `ClassCastException` or `ArrayStoreException`, with no backtrace and its detail message cleared. A hot `NullPointerException` site has two frames and a message at first, and after about 5,300 loop iterations has no frames and a `null` message, on both 27.0.1 and 25.0.3. On both releases, a second site in a method with a local `catch` prints no frames and a `null` message on its first exception ever. With `-XX:-OmitStackTraceInFastThrow` on 27.0.1, no iteration lost its frames and the last still had its message. `NullPointerException`'s documentation allows for the missing frames. `Throwable.java` is the same in JDK 25 and JDK 27, and those flags have the same defaults in both releases.
- How does overriding fillInStackTrace to return this differ from passing writableStackTrace=false?Both skip the walk and leave `getStackTrace()` empty. The override leaves the private `stackTrace` field at its empty sentinel, so a later `setStackTrace` still stores a trace. The constructor writes `null` there, so `setStackTrace` only validates its argument. The override is also a virtual method called from `Throwable`'s constructor, so it runs before the subclass's own fields are initialised.
- Does a stackless exception make throwing it free?Only when inlining makes it so. It removes the capture, and reusing one instance removes the construction. The JVMS model still searches handlers and pops frames, but C2 can compile a throw inlined into its catching frame to a direct branch. Timed once on OpenJDK 27.0.1 without JMH, a shared instance caught one frame up cost about the same as a sentinel return when inlined, and roughly 55 ns a throw when inlining was disabled. It still reads as a non-local jump.
- A production log shows NullPointerException with no frames and no message. What is the likely cause?HotSpot's fast throw is the likely cause. With `OmitStackTraceInFastThrow`, true by default, C2-compiled code can use a preallocated exception with no backtrace once a site keeps throwing, or once another site in a method with a local handler has thrown the same way. So this site's first occurrence may already lack frames. Search earlier in the log for the method's first throws, or restart with `-XX:-OmitStackTraceInFastThrow` to keep traces at the price of building them.
Recording a Throwable's stack is like taking a film photo of everyone in the queue each time an incident form is opened: the shot is taken at once, whether or not anyone looks, and developing the film waits until someone asks to see it. A stackless exception is a pre-printed form with no photo: quick to hand out, useless for working out who was in the queue.
- Creating an exception costs about the same as any other object; only throwing it is expensive.
- The cost of a stack trace is the same however deep the call stack is.
- The full StackTraceElement array is built inside the exception's constructor.
- writableStackTrace=false only blocks setStackTrace; the frames are still captured.
- Every custom exception should be stackless, because stack traces are just overhead.
- One shared exception instance is safe to reuse with suppression left enabled.
- Throwable constructor with writableStackTrace
- Java 1.7
- Throwable.fillInStackTrace
- Java 1.0
- Throwable.getStackTrace
- Java 1.4
- Throwable.addSuppressed
- Java 1.7
Assumes Java 27; Throwable.java is unchanged from 25, and 25 has the same MaxJavaStackTraceDepth and OmitStackTraceInFastThrow defaults.
context
- Throwable (Java SE 27 & JDK 27)docs.oracle.com
- Throwable.java at jdk-27-gagithub.com
- Chapter 2. The Structure of the Java Virtual Machinedocs.oracle.com