In C++, how should a worker std::thread report an exception to the thread that joins it, and what happens if it does not?
answer
- exceptions do not cross threads
- capture inside catch (...)
- a nullable owning handle
- rethrow after join
basics
~10 sCatch everything inside the thread function, store std::current_exception() in a std::exception_ptr, and after join() call std::rethrow_exception on the joining thread. An exception that escapes a std::thread's initial function calls std::terminate.
solid answer
~40 sExceptions propagate only within one thread: the handler search never crosses into the thread that created the worker, and if the worker's initial function exits via an exception the program calls `std::terminate`. So the worker wraps its body in `try { ... } catch (...) { failure = std::current_exception(); }`. `std::exception_ptr` is a nullable handle that keeps the exception object alive. After `join()`, whose return synchronizes with the thread's completion so reading `failure` is not a data race, the main thread tests it and calls `std::rethrow_exception(failure)` inside its own `try`, catching by the real type. Whether `current_exception` and `rethrow_exception` hand over the same object or a copy is unspecified, so several threads rethrowing one pointer must not mutate it.
code
cpp · 28 lines#include <exception>
#include <iostream>
#include <stdexcept>
#include <thread>
void import_chunk(int id) {
if (id == 2) throw std::runtime_error("chunk 2: bad checksum");
}
int main() {
std::exception_ptr failure; // null until a worker fails
std::thread worker([&failure] {
try {
for (int id = 0; id < 4; ++id) import_chunk(id);
} catch (...) {
failure = std::current_exception(); // capture, do not let it escape
}
});
worker.join(); // join orders the write before the read
if (failure) {
try {
std::rethrow_exception(failure); // rethrown on the main thread
} catch (const std::exception& e) {
std::cout << "worker failed: " << e.what() << '\n';
}
}
}go deeper
Remember that an exception thrown in a std::thread does not reach the code that started the thread; an escaped one ends the program.
Explain the trio std::current_exception, std::exception_ptr and std::rethrow_exception, and why the read happens only after join().
Build thread entry points that always capture, give each worker its own slot, rethrow on the joining thread, and avoid make_exception_ptr slicing and shared mutation of a rethrown object.
Standardise one task abstraction in the codebase, whether futures or a thread pool, so exception transport is solved once instead of in every hand-written thread.
## Why the exception cannot simply propagate C++ exception handling is defined per thread. When a handler search finds no match in a `try` block, it "continues in a dynamically surrounding try block **of the same thread**". There is no surrounding block in the thread that created the worker; the worker's call stack ends at its initial function. The standard lists, among the cases that call `std::terminate`, "when execution of the initial function of a thread exits via an exception". With libc++ that looks like this: ```plaintext libc++abi: terminating due to uncaught exception of type std::runtime_error: lost ``` `join()` does not rethrow anything; the program is gone before it could. ## The tools in `<exception>` | Facility | What it does | |---|---| | `std::exception_ptr` | a nullable, copyable handle to an exception object; equal pointers refer to the same exception; default-constructed is null | | `std::current_exception()` | inside a handler, returns an `exception_ptr` to the currently handled exception or to a copy of it; outside one, a null pointer | | `std::rethrow_exception(p)` | throws the object `p` refers to, or a copy; `p` must not be null | | `std::make_exception_ptr(e)` | creates an `exception_ptr` to a copy of `e`, as if by `throw e;` then `current_exception()` | The standard notes that an implementation can use a reference-counted smart pointer for `exception_ptr`, and the object stays valid as long as any `exception_ptr` refers to it. ## The pattern for the importer's worker 1. Declare `std::exception_ptr failure;` in the joining thread. 2. In the worker, wrap the whole body in `try { ... } catch (...) { failure = std::current_exception(); }`. Use `catch (...)`, not `catch (const std::exception&)`, so that non-standard exception types are captured too. 3. `join()` the worker. The completion of the thread **synchronizes with** the successful return of `join()`, so the write to `failure` happens before the read; no atomic is needed for this one hand-off. 4. If `failure` is non-null, call `std::rethrow_exception(failure)` inside a `try` and catch by `const` reference to the real type. For several workers, give each its own `exception_ptr` slot (for example, a `std::vector<std::exception_ptr>` sized up front) so that no two threads write the same object. ## Subtleties an interviewer probes - **Copy or same object.** It is unspecified whether `current_exception` copies the exception and whether `rethrow_exception` throws the same object or a copy. The standard warns that if it rethrows the same object, concurrent access to that object from several threads can race. Treat a captured exception as read-only. - **Copy failures.** If copying the exception is needed and fails, `current_exception` returns a pointer to the exception that the copy threw, or to `std::bad_exception`; if allocation fails it can refer to `std::bad_alloc`. - **`make_exception_ptr(e)` slices.** Called with a `const std::exception&` parameter, it copies `e` by its static type. Inside a handler, `current_exception()` is the right call. - **Futures do this for you.** `std::promise::set_exception` and `std::async` store an `exception_ptr` and `future::get()` rethrows it; that machinery belongs with futures and async. ## Many workers: first failure or all failures An importer that splits a file into chunks across several workers has to decide what to report: - **First failure**: give each worker its own `std::exception_ptr` slot, join them all, then rethrow the first non-null slot in chunk order. Rethrowing before every worker is joined would run the destructor of a still-joinable `std::thread` during unwinding, which itself calls `std::terminate`. - **All failures**: collect the non-null slots into a list and wrap them in an aggregate exception type of your own, or report each one before throwing a summary. - **Stop early**: a shared `std::atomic<bool>` (or a `std::stop_token` with `std::jthread` in C++20) lets the first failing worker ask the others to stop, so the importer does not keep parsing a file it will reject anyway. In every variant the rule stays the same: capture in the worker, synchronize by joining, rethrow on the joining thread. ## A checklist for thread entry functions - Every thread function catches everything at its outermost level. - Nothing is rethrown before `join()` has returned. - Each worker writes only its own result or exception slot. - The joining thread rethrows inside its own `try`, so the error reaches the importer's ordinary handlers.
- Why should the worker catch with catch (...) rather than catch (const std::exception&)?Code can throw any copyable type: an `int`, a third-party error class, a type with a private `std::exception` base. A `std::exception` handler misses those, and a miss in a thread's initial function calls `std::terminate`. `catch (...)` with `std::current_exception()` captures every exception, and the joining thread decides how to classify it when it rethrows.
- Is it safe for two threads to call std::rethrow_exception on copies of the same exception_ptr?Calling `rethrow_exception` on pointers to the same exception does not itself introduce a data race. But because the implementation may throw the same object rather than a copy, both handlers can end up referring to one exception object; reading it is fine, mutating it from both threads is a race. Catch by `const` reference and treat the object as immutable.
- join() rethrows the exception that ended the thread.
- An exception escaping a std::thread just ends that thread quietly.
- std::exception_ptr needs std::atomic to be read after join().
- std::make_exception_ptr(e) on the handler parameter captures the full dynamic type.
- Catching const std::exception& in the thread function captures every exception.