Lesson · Multithreading Fundamentals
Uncaught Exceptions: the handler chain and the silent Future
15 min readUncaught Exception Handler
When a thread throws and nobody catches, the thread dies and the JVM resolves a chain of handlers to report what happened. The chain has a fixed order, it only reports, and one common executor path bypasses the reporting entirely: submit() captures the throwable inside a Future that nobody reads. Knowing both shapes is the difference between a loud crash and a silent one.
When nobody catches: the thread dies alone
Every thread has its own call stack, and an exception travels up that stack only. When a thread's run() throws and no frame on that stack catches it, the thread terminates. The exception never becomes main's problem, and by default it does not stop the program either.
Silence would hide real bugs, so the JVM resolves a handler for the throwable before letting the thread die. With nothing configured anywhere, the last resort prints the familiar report to System.err: the thread name, the throwable and the stack trace.
Two facts are worth separating here. The thread is gone, so anything it was responsible for is now nobody's job. The process is unaffected: other threads keep running, and the JVM stays up as long as one non-daemon thread is alive.
Exception in thread "t1" java.lang.IllegalStateException: boom at demo.UncaughtHandlerDemo.explode(UncaughtHandlerDemo.java:38) at java.base/java.lang.Thread.run(Thread.java)
An uncaught exception kills a thread, not the process. The JVM's job in that moment is reporting, not recovery.
The handler chain, in order
The lookup has a fixed order. First the handler set on the thread itself, then the thread's ThreadGroup.uncaughtException, and finally the global default installed with Thread.setDefaultUncaughtExceptionHandler. If nothing exists anywhere, the report falls back to System.err.
The default ThreadGroup implementation delegates to its parent group, so a throw climbs from the innermost group to the root and the default handler is consulted at the top. A group that overrides uncaughtException ends that climb for its threads, which is why old code that subclasses ThreadGroup can swallow reports without anyone noticing.
The chain is a reporting mechanism, never control flow. It runs after the thread is already dying, so it can log, alert or increment a counter, and it cannot rescue the thread or hand the throwable to anyone else.
- Per-thread handler:
thread.setUncaughtExceptionHandler(h). First in line, and the only place task-specific context exists. - The thread's ThreadGroup, walking up through parent groups that override
uncaughtException. - The global default:
Thread.setDefaultUncaughtExceptionHandler(h), once no group claimed the throw. - System.err: the built-in last resort, which prints the thread name, the throwable and the stack trace.
The chain decides who reports, never who is rescued. By the time a handler runs, that thread is already dead.
The handler chain
first match wins; System.err is the floorrun() throws and nobody caught it
The thread terminates; the JVM now resolves a handler for the throwable.
thread.setUncaughtExceptionHandler(h)
First in line, and the only place that knows the task context.
group.uncaughtException(thread, thrown)
The default implementation delegates to the parent group. A group that overrides the method ends the climb.
Thread.setDefaultUncaughtExceptionHandler(h)
Consulted once no group claimed the throw. Logging and alerting belong here.
System.err
The built-in report: thread name, throwable and stack trace, with nothing else listening.
Exception in thread "t1" java.lang.IllegalStateException: boom
the same throw inside an executor task
Which of the two report paths runs depends on the submit call, not on the task.
wait, which method ran?
submit(task)
Future holds the throwable
No handler runs and nothing prints. get() later rethrows it as ExecutionException, and the pool never notices: it saw a completed task.
execute(task)
the worker chain runs
The throwable reaches the handler chain of the pool worker and is reported. The pool replaces that worker and keeps running.
Handlers report; they never rescue, and the throwable is always out of their hands by the time they run. The submit path never reaches one at all.
Setting handlers in practice
A handler is one method, uncaughtException(Thread t, Throwable e), and the two arguments are exactly the context a cross-cutting logger wants: which thread died and what killed it. The idiomatic default handler logs once with the thread name and stops there.
On a per-thread handler you can add context the global one cannot know, such as a job id or a tenant, and you can still call the default handler yourself with the same arguments when you want the usual report as well.
Two rules keep this honest: install the default handler as early as possible, and never let library code overwrite the application's handler, which would delete its logging policy. Keep the handler defensive too, because a failure inside a handler produces no second, better report.
- Default handler: one place, installed at startup. It is the last net for reporting, not the strategy.
- Per-thread handler: context. When a task has an id, the handler on its thread is the only place that knows it.
- Handlers run after death. They cannot retry the work, restart the thread or repair state; they can log, alert and wake a supervisor.
- Libraries never seize the global default. A dependency that sets it has replaced the host application's policy; wrappers and documented hooks are the polite alternatives.
Handle inside the task when you can; a handler is for the exceptions that nobody could have handled.
Executors: execute() reports, submit() stores
Executor tasks change the story twice. With execute(Runnable), the worker thread runs your task, the throwable escapes the task, and it reaches that worker's handler chain. The pool then replaces the dead worker and keeps running: the report appears, and the pool survives.
With submit(...), the executor wraps the task and captures the throwable inside the returned Future. Nothing prints, no handler runs, and the worker does not even die, because from the pool's point of view the task completed normally with a stored failure.
If nobody reads that Future, the failure is parked silently. It is the most common way a real bug survives in production looking like a success, because the line that would have alerted you is the get() nobody wrote.
| Path | Where the throwable goes | Who reports it |
|---|---|---|
| new Thread(task) | the thread's handler chain | per-thread handler, then group, default, stderr |
| execute(task) on a pool | the worker thread's handler chain | the same chain, from the pool worker; the worker is replaced |
| submit(task) | into the Future | nobody, until someone calls get() |
| submit(task) plus get() | rethrown as ExecutionException | your catch block, with the cause inside |
- execute() routes to the handler chain. No Future exists, so the throwable belongs to the worker thread, and the pool replaces that worker.
- submit() stores the throwable in the Future. The pool sees a completed task, and the failure waits for a reader.
- The pool survives both paths. Worker death and task failure are different events, and the executor handles the first so you can handle the second.
submit() swallows exceptions into a Future you may never read; if you never get(), you never see it.
Handler lab · what actually prints
pick a scenario, then press Run$ java UncaughtHandlerDemo --raw
press Run to execute this scenario
Two paths report (the handler chain and execute()), two stay quiet until the Future is read. The pool survives all four.
Reading a Future without surprises
Future.get() rethrows the stored failure as ExecutionException, with your original exception as its cause. The wrapping is deliberate: the method's own checked exceptions, InterruptedException and TimeoutException from the timed overload, must stay distinguishable from the task's failure.
CompletableFuture changes the container, not the idea: a failure is captured in the future and delivered on join() as CompletionException, and the callbacks receive it as well. Cancellation adds CancellationException to the same vocabulary.
Unwrap where you log. e.getCause() carries the real stack trace, and reporting the ExecutionException alone reads like a framework error while the actual bug stays buried.
Future<Integer> f = pool.submit(() -> compute(input)); try { int result = f.get(); // blocks; throws if the task failed } catch (ExecutionException e) { throw new BatchException("task failed", e.getCause()); // unwrap: the cause is the story } catch (InterruptedException e) { Thread.currentThread().interrupt(); // keep the cancellation contract (forward link: thread API) throw new BatchException("interrupted while waiting", e); }
ExecutionException is the envelope; getCause() is the letter.
Where to handle: task first, hook last
For pools, the hook that reaches every worker is the pool's ThreadFactory (forward link: daemon threads): the thread it returns is the one whose handler chain runs on the execute() path, so the factory is where a uniform worker policy is installed once.
- Inside the task, when the task can answer. Known failure modes belong in the code that has the context to correct them or rethrow them with meaning.
- A per-task wrapper, when the task can only report. Wrapping the Runnable or Callable to catch and log with the job id keeps the policy uniform without touching the global default.
- The thread's handler, when nothing else ran. It catches exactly the throwables that escaped every catch: a broken assumption, a crash in a callback, an error in a worker loop.
- The global default, once, for the last report. Logging and alerting go in at startup, it should fire rarely, and every firing is a defect to fix.
By the time a handler runs, the only useful action left is telling somebody.
The two traps in one sentence
The two traps sit next to each other: the handler chain exists for exceptions that escaped every catch, and submit() makes sure such an exception escapes into a Future nobody looks at.
So the working rules are short. Handle in the task, install one default handler for reporting, keep the Future when you submit, and read it. A pool whose failures you never read is a pool whose failures you do not have.
A silently failing task is worse than a crashing thread, because only one of them tells you.
Submit a task, read a Future, or lose the failure
submit() captures the exception inside the returned Future and prints nothing; execute() routes it to the worker thread's handler chain. A task that throws under submit() is completed from the pool's point of view, so an unread Future is a deleted stack trace. Keep the Future and call get() (or attach whenComplete), and wrap tasks with a reporting wrapper wherever the call sites cannot be trusted to read it.
Interview angles
What happens when a thread throws an uncaught exception?+
The thread terminates and the JVM resolves a handler for the throwable: per-thread handler, then the ThreadGroup chain, then the global default, then System.err. Other threads keep running, so the process usually survives.
How is the handler chain ordered, and where do you install a global handler?+
Thread first, then ThreadGroup (delegating up through parents), then the default installed with Thread.setDefaultUncaughtExceptionHandler, then stderr. Install the default at startup; a group that overrides uncaughtException ends the climb for its threads.
Because the default ThreadGroup delegates to its parent, the global default is consulted at the top of the group tree. That is also why the javadoc warns the default handler should not call back into the thread's group: the delegation would recurse.
Why does a task submitted to an executor print nothing when it throws?+
submit() captures the throwable inside the returned Future, so no handler runs and nothing is printed. It surfaces only through get(), wrapped in ExecutionException. Keep the Future and read it, or use execute() when reporting is what you want.
Common misconception: People expect the pool to report failures the way execute() does. Under submit() the pool believes the task finished, so an unread Future is the only place the failure exists.
What is the difference between execute() and submit() for error handling?+
execute() has no Future, so a thrown exception reaches the worker thread's handler chain and the pool replaces the dead worker. submit() stores the exception in the Future, the worker survives, and the failure stays invisible until get() is called.
What can an uncaught exception handler actually do?+
Report: log with the thread name, alert, increment a counter, trigger a supervisor. It runs after the thread is dying, so it cannot retry the work, restart the thread or repair state, and it cannot hand the throwable to another handler as control flow.
Keep handlers tiny and non-throwing, because a failure inside a handler produces no second, better report. In libraries, do not install a global default: replacing the application's handler deletes its logging policy.
Logs show ExecutionException with no stack trace of the real bug. What went wrong?+
The log line printed only the wrapper. Future.get() wraps the task's failure with the original throwable as the cause, so logging e.getCause() (or the full chain) is what reveals the bug; and if the Future was never read at all, nothing would have been logged in the first place.
Follow-up: How would you make a shared pool wrapper report job context without changing every call site?