Quick revision
The short answer
Most of the cost of an exception is paid when it is created, not when it is thrown: the Throwable constructor calls fillInStackTrace, which walks the thread's stack and records every frame, so the cost grows with stack depth. Throwing and catching inside one compiled method can be almost free, while unwinding across many frames costs more. We can reduce the cost with the protected Throwable constructor that sets writableStackTrace to false, or with preallocated exceptions, but both lose context; HotSpot does something similar automatically for hot implicit exceptions, which can hide details in logs. The best fix for a parser is not to use exceptions for expected outcomes at all.
What to remember
In this answer, we saw that the main cost of an exception is fillInStackTrace walking the stack when it is constructed, while throwing and catching within inlined compiled code can be cheap and unwinding across many frames costs more. We can skip stack traces with Throwable's writableStackTrace=false constructor or use preallocated exceptions, at the price of lost context, and HotSpot's OmitStackTraceInFastThrow does this automatically for hot implicit exceptions. The best fix for something like a parser is to stop using exceptions for expected outcomes and return a result or check first.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Most of the cost of an exception is paid when it is created, not when it is thrown: the Throwable constructor calls fillInStackTrace, which walks the thread's stack and records every frame, so the cost grows with stack depth. Throwing and catching inside one compiled method can be almost free, while unwinding across many frames costs more. We can reduce the cost with the protected Throwable constructor that sets writableStackTrace to false, or with preallocated exceptions, but both lose context; HotSpot does something similar automatically for hot implicit exceptions, which can hide details in logs. The best fix for a parser is not to use exceptions for expected outcomes at all.
Why this question is asked
Exceptions are often blamed for being slow, and sometimes the blame is fair: a parser that throws on every malformed token, or a lookup that signals "not found" with an exception, can spend most of its CPU building stack traces nobody reads. But the cost is very uneven, and guessing where it comes from leads to the wrong fix. Interviewers ask this to see whether we know what actually happens inside the JVM and can choose between the tools available. In this answer, we will break the cost into its parts, see why stack traces dominate, look at how the JIT can make some throws cheap, go through the ways to reduce the cost and what each one sacrifices, and end with the redesign that usually works best.
1Where the Cost Comes From
An exception's life has three stages, and each has a different cost. First, creation: new ParseException(...) allocates the object and, in the Throwable constructor, calls fillInStackTrace(). Second, throwing: the JVM looks for a handler, first in the current method's exception table, then in each caller in turn, popping frames as it goes; this is called unwinding. Third, use: if anyone calls getStackTrace() or prints the exception, the raw stack data is turned into StackTraceElement objects with class names, method names and line numbers.
The first stage is usually the expensive one. fillInStackTrace walks the whole stack of the current thread and records every frame, whether or not the exception will ever be logged. In a Spring application, a call from a controller into a parser can easily be 80 to 150 frames deep, counting the framework, proxies and filters. Recording all of them for every malformed token adds up quickly.
| Stage | What happens | Cost grows with |
|---|---|---|
| Create | allocate, fillInStackTrace walks the stack | stack depth (usually the main cost) |
| Throw | find a handler, unwind frames | frames between throw and catch |
| Use | build StackTraceElements, format text | only paid if printed or inspected |
2Measuring It
The only reliable way to know the cost on our code and hardware is a benchmark with JMH, the Java Microbenchmark Harness. Here is the shape of one that separates stack trace collection from the rest.
Notice that we return the exception from the benchmark methods. The reason is that the JIT can remove work whose result is never used, and an exception that is created and dropped might be optimized away, making the benchmark meaningless.
3When Throwing Is Almost Free
Throwing itself can be very cheap. When the JIT compiler inlines the method that throws into the method that catches, it can see both ends and turn the throw into a simple jump to the handler, with no unwinding at all. If, in addition, the exception object never escapes and its stack trace is never used, escape analysis may avoid creating it, in some cases.
So a throw and catch within the same hot, compiled code path can cost little more than an if statement. The expensive cases are the opposite: a throw from deep inside library code, caught many frames up, in code paths the JIT has not inlined together, with a new exception and full stack trace each time. That describes most real parsers and validators, which is why the problem shows up there.
4Ways to Reduce the Cost, and What Each Sacrifices
The direct way to skip stack trace collection is the protected Throwable constructor with four arguments: message, cause, enableSuppression and writableStackTrace. Passing false for writableStackTrace means fillInStackTrace is not called and getStackTrace() returns an empty array. A subclass can also override fillInStackTrace to return this without doing anything, an older idiom with the same effect. Either way, we keep the message and the type but lose the location, so if such an exception ever reaches a log, it says what happened but not where.
A second option is a preallocated exception: one static final instance thrown again and again. It costs nothing to throw, but it cannot carry a per-call message, such as the line and column of the bad token, and its stack trace, if any, points at wherever it was first created, which is misleading. It also must never be modified, because all threads share it.
HotSpot uses the preallocated approach itself. For implicit exceptions thrown very frequently from compiled code, such as NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException and ClassCastException, the OmitStackTraceInFastThrow optimization, on by default, eventually throws a shared instance with no stack trace and no message. That is why some services show bare NullPointerException lines in logs after running for a while. It makes those exceptions cheap, but it hides exactly the details we need to fix the bug; -XX:-OmitStackTraceInFastThrow turns it off.
5The Best Fix: Do Not Use Exceptions for Expected Outcomes
In a parser, malformed input is not exceptional; it is part of the job. So the most effective fix is to stop using exceptions for that case. The parser checks before it acts, or returns a result that says success or failure, and exceptions are kept for truly unexpected failures such as an I/O error.
The result type carries more useful information than the exception did, the exact position and reason, and costs only a small allocation. Callers handle both cases in a switch. If an exception-based API must stay for compatibility, a stack-trace-free exception type is the pragmatic middle ground, and we document that it carries no location.
6Follow-up questions
Does try/catch cost anything when no exception is thrown?
Practically no. A try block only adds an entry to the method's exception table, which is consulted only when an exception is actually thrown. The normal path runs the same instructions with or without the try.
How do we find out whether exceptions are a real cost in production?
A profiler such as async-profiler or JDK Flight Recorder shows time in fillInStackTrace and related frames. JFR's jdk.ExceptionStatistics event gives a cheap count of throwables created, and jdk.JavaExceptionThrow can record each one with its stack, but it is off by default because it is expensive, so it should be enabled only briefly.
7Conclusion
In this answer, we saw that the main cost of an exception is fillInStackTrace walking the stack when it is constructed, while throwing and catching within inlined compiled code can be cheap and unwinding across many frames costs more. We can skip stack traces with Throwable's writableStackTrace=false constructor or use preallocated exceptions, at the price of lost context, and HotSpot's OmitStackTraceInFastThrow does this automatically for hot implicit exceptions. The best fix for something like a parser is to stop using exceptions for expected outcomes and return a result or check first.
Open with
Most of the cost is paid at construction. The Throwable constructor calls fillInStackTrace, which walks the current thread's stack and records every frame, so in a deep Spring call stack of a hundred frames or more, that is real work, and it is paid even if nobody ever prints the trace.
Then, if they want more
Throwing itself can be cheap: if the JIT inlines the thrower into the catcher, the throw becomes a jump, but unwinding across many non-inlined frames costs more. Turning the trace into StackTraceElements is only paid when someone prints or inspects it.
To reduce the cost, Throwable has a protected constructor with writableStackTrace false, which skips the stack walk, or we can override fillInStackTrace. Preallocated exceptions are even cheaper but cannot carry per-call details. Both lose the location, which hurts debugging.
HotSpot does something similar automatically with OmitStackTraceInFastThrow, which throws a preallocated NullPointerException or similar with no trace for hot implicit exceptions, and that is why logs sometimes show bare NPEs.
For a parser, though, the best fix is not to use exceptions for expected outcomes: check first or return a result type with the position and reason of the error, and keep exceptions for unexpected failures. I would measure with JMH and a profiler before and after.
About this answer
- Last updated
- 12 November 2026
- 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.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
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 makes exceptions expensive in Java, and how can you reduce the cost when exceptions...": https://scrivio-interview-library.netlify.app/java/exceptions/87394908fd/