What happens when a thread throws
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)When an exception escapes a thread's run(), only that thread dies. The rest of the program carries on, often without noticing, so worker failures must be caught and reported on purpose.
An exception ends only that thread
An uncaught exception is one that leaves run() without being caught. It ends only the thread it happened in. The JVM prints Exception in thread "<name>" and the stack trace to System.err, and every other thread, main included, keeps running.
Example 1 · A failing worker does not stop main
public class WorkerFailsDemo { public static void main(String[] args) throws InterruptedException { int[] marks = {72, 85, 64}; int students = 0; // bug: should be marks.length
Thread avg = new Thread(() -> { int sum = 0; for (int m : marks) { sum += m; } System.out.println("Average: " + sum / students); }, "avg-worker");
avg.start(); avg.join(); System.out.println("main: avg-worker state = " + avg.getState()); System.out.println("main: still running, serving other students"); }}Exception in thread "avg-worker" java.lang.ArithmeticException: / by zero at WorkerFailsDemo.lambda$main$0(WorkerFailsDemo.java:11) at java.base/java.lang.Thread.run(Thread.java:1583) main: avg-worker state = TERMINATED main: still running, serving other students
What this code does
sum / studentsthrowsArithmeticExceptiononavg-worker. Only that thread ends; the JVM prints its name and the stack trace onSystem.err.maincarries on: the worker isTERMINATED, andmainprints its own lines and finishes normally. The order of the error text and the normal output can vary, because they go to two different streams.
The program does not crash as a whole. It can carry on with a missing result and no one notices, unless someone was watching for the failure. That silent half-failure is the real danger.
Why main cannot catch another thread's exception
A try/catch catches only exceptions thrown on its own thread's call stack. The worker's exception is thrown on the worker's stack, after start() has already returned, so a try around start() or join() in main never sees it.
Example 2 · try/catch in main does not see it
public class MainCannotCatchDemo { public static void main(String[] args) throws InterruptedException { Thread booker = new Thread(() -> { throw new IllegalStateException("Seat 14 already booked"); }, "seat-booker");
try { booker.start(); booker.join(); System.out.println("main: join returned normally"); } catch (IllegalStateException e) { System.out.println("main: caught " + e.getMessage()); // never runs } }}Exception in thread "seat-booker" java.lang.IllegalStateException: Seat 14 already booked at MainCannotCatchDemo.lambda$main$0(MainCannotCatchDemo.java:4) at java.base/java.lang.Thread.run(Thread.java:1583) main: join returned normally
What this code does
- The exception is thrown on
seat-booker's call stack, notmain's.main'scatchnever runs, andjoin()returns normally although the booking failed. - This is why worker failures must be reported by the worker itself: caught inside the task, or passed to a handler.
join() does not rethrow it either; it simply returns when the thread has ended, whether normally or with an exception. To learn about a failure, the worker must report it: by catching it inside the task, or through an uncaught exception handler.
UncaughtExceptionHandler
An UncaughtExceptionHandler is a callback the JVM calls when an exception escapes run(). It receives the thread and the exception: t.setUncaughtExceptionHandler((thread, e) -> ...). It runs on the dying thread itself, just before that thread ends, so join() returns only after the handler has finished.
Example 3 · An uncaught exception handler on one thread
public class HandlerDemo { public static void main(String[] args) throws InterruptedException { Thread booker = new Thread(() -> { System.out.println("seat-booker: booking seat 14"); throw new IllegalStateException("Seat 14 already booked"); }, "seat-booker");
booker.setUncaughtExceptionHandler((thread, e) -> System.out.println("ALERT: " + thread.getName() + " failed: " + e.getClass().getSimpleName() + ": " + e.getMessage()));
booker.start(); booker.join(); System.out.println("main: booker state = " + booker.getState()); }}seat-booker: booking seat 14 ALERT: seat-booker failed: IllegalStateException: Seat 14 already booked main: booker state = TERMINATED
What this code does
- The handler receives the dying thread and its exception. It replaces the default
Exception in threadprintout, so nothing goes toSystem.errhere. - The handler runs on
seat-bookerbefore it ends, andjoin()waits for the thread to end, so the alert always comes beforemain's line.
Example 4 · One default handler for every worker
public class DefaultHandlerDemo { public static void main(String[] args) throws InterruptedException { Thread.setDefaultUncaughtExceptionHandler((thread, e) -> System.out.println("LOG " + thread.getName() + ": " + e.getClass().getSimpleName()));
String[] orders = {"Laptop", "", "Phone case", null}; for (int i = 0; i < orders.length; i++) { String order = orders[i]; Thread t = new Thread(() -> { if (order.isEmpty()) { throw new IllegalArgumentException("empty order"); } System.out.println(Thread.currentThread().getName() + ": packed " + order); }, "packer-" + (i + 1)); t.start(); t.join(); // one at a time, only to keep the output in order } System.out.println("main: all orders handled"); }}packer-1: packed Laptop LOG packer-2: IllegalArgumentException packer-3: packed Phone case LOG packer-4: NullPointerException main: all orders handled
What this code does
- None of the threads has its own handler, so the default handler logs both failures: the
IllegalArgumentExceptionand aNullPointerExceptionthe code did not expect. packer-4got anullorder, which nobody planned for. A default handler is a good safety net for surprises like this: they are logged in one place instead of being lost inSystem.err.
Thread.setDefaultUncaughtExceptionHandler(...) sets one handler for every thread that has no handler of its own. If neither is set, the JVM prints the usual Exception in thread message.
Logging failures from worker threads
Catch exceptions inside the task whenever you can do something useful: log the failure with the thread's name, store it next to the result, or retry. The main thread then checks each task's outcome after join() and decides what to do.
Example 5 · Catch inside the task and report the outcome
class FeeTask implements Runnable { private final String student; private final String amountText; int amount; // the result, if it worked Exception error; // the failure, if it did not
FeeTask(String student, String amountText) { this.student = student; this.amountText = amountText; }
@Override public void run() { try { amount = Integer.parseInt(amountText); } catch (NumberFormatException e) { error = e; System.out.println("[" + Thread.currentThread().getName() + "] could not read fee for " + student + ": " + e.getMessage()); } }
String student() { return student; }}
public class ReportFailuresDemo { public static void main(String[] args) throws InterruptedException { FeeTask[] tasks = { new FeeTask("Asha", "45000"), new FeeTask("Ravi", "4S000"), new FeeTask("Meena", "38000") }; Thread[] threads = new Thread[tasks.length]; for (int i = 0; i < tasks.length; i++) { threads[i] = new Thread(tasks[i], "fee-" + (i + 1)); threads[i].start(); } for (Thread t : threads) { t.join(); }
int total = 0; int failed = 0; for (FeeTask task : tasks) { if (task.error == null) { total += task.amount; } else { failed++; } } System.out.println("Collected: Rs " + total + ", failed records: " + failed); }}[fee-2] could not read fee for Ravi: For input string: "4S000" Collected: Rs 83000, failed records: 1
What this code does
- Each task catches the error it expects, logs it with its thread name and keeps it in
error. The thread itself ends normally. - After joining,
mainsees every outcome and can report the partial result honestly instead of silently showing a wrong total. Only one record fails, so the log line is the only line printed by a worker.
Keep a handler as a safety net for anything you did not expect. Later, the Executors module shows Future.get(), which hands a task's exception back to the caller wrapped in an ExecutionException.
Next step
Check your understanding
12 quick questions