Uncaught Exception Handler Threads
Route exceptions escaping a raw thread to the default uncaught exception handler, and see why pooled submit() tasks keep theirs hidden inside the Future.
Code
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CrashReporter {
public static void main(String[] args) throws InterruptedException {
Thread.setDefaultUncaughtExceptionHandler((thread, thrown) ->
System.out.println("handler caught in " + thread.getName()
+ ": " + thrown.getMessage()));
// 裸线程里逃逸的异常会走到默认 UncaughtExceptionHandler
Thread raw = new Thread(() -> {
throw new IllegalStateException("boom from raw thread");
}, "raw-worker");
raw.start();
raw.join();
// submit() 的任务异常被 Future 承载:worker 线程不死,UEH 不触发
try (ExecutorService pool = Executors.newSingleThreadExecutor()) {
Callable<Void> task = () -> {
throw new IllegalStateException("boom from pooled task");
};
try {
pool.submit(task).get();
} catch (ExecutionException wrapped) {
System.out.println("future rethrew cause: " + wrapped.getCause().getMessage());
}
}
System.out.println("main finished");
}
}How the snippet works
Uncaught Exception Handler Threads keeps everything in the class CrashReporter.
The try-with-resources form guarantees each declared resource is closed even when the body throws. A IllegalStateException is thrown unconditionally at its throw site — no input check sits in front of it.
Using it
Running the file prints labeled results such as handler caught in, future rethrew cause:, main finished — each operation’s effect is visible in the output.
Key statements
try (ExecutorService pool = Executors.newSingleThreadExecutor()) {
Callable<Void> task = () -> {
throw new IllegalStateException("boom from pooled task");
};
try {
pool.submit(task).get();
} catch (ExecutionException wrapped) {
System.out.println("future rethrew cause: " + wrapped.getCause().getMessage());
}
}
throw new IllegalStateException("boom from raw thread");
Thread.setDefaultUncaughtExceptionHandler((thread, thrown) ->
System.out.println("handler caught in " + thread.getName()
+ ": " + thrown.getMessage()));
Interactive Tools for This Topic
FAQ
- Does the snippet validate its input?
- No. There is no input validation in the snippet — the `IllegalStateException` is raised unconditionally at its site, with no check in front of it.
- What does Uncaught Exception Handler Threads print when run?
- Run it as a complete program — the output lines carry labels such as `handler caught in`, `future rethrew cause:`, `main finished`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.