Video in progress

Strong Middle ☕ Core Java

Why is creating an exception expensive, and how can you reduce that in high-load code?

Most of the cost goes to fillInStackTrace(): the constructor walks the whole stack. Don't use exceptions for ordinary control flow (instead of if/else), and if you need to, create an exception without a stack trace.

📖 Answer

When you write new RuntimeException(), the JVM walks the current thread's stack and collects information about every frame. If the stack is deep (Spring + filters + proxies: 100+ frames is normal), this is much more expensive than the throw/catch itself.

A typical problem: validation or a "not found" case is handled with an exception and thrown thousands of times per second. In the profiler, Throwable.fillInStackTrace shows up at the top.

What you can do:

// 1) A business error that doesn't need a stack trace
public class LimitExceeded extends RuntimeException {
    public LimitExceeded(String msg) {
        super(msg, null, false, false); // suppression and stack trace are off
    }
}
  1. For flow control, return a result instead of throwing: Optional, boolean, a sealed Result type.
  2. You can also create an exception once and rethrow it, but the trace will be wrong, so only do this with a trace-less exception.

One catch: if you turn off the trace, it's hard to find the real error in the logs in prod. So this is only for expected business cases that happen often.

Also: HotSpot may drop the trace for internal exceptions that are thrown very often (NullPointerException and others). You turn that off with -XX:-OmitStackTraceInFastThrow; if you see an NPE with no trace in the log, that's why.