skip to content

Inside a C++ handler catch (const std::exception& e), how does throw; differ from throw e;?

level: middleimportance: must knowfreq 65%

answer

  1. same object or a new one
  2. static type of the operand
  3. outer handlers for the derived type
  4. no current exception means terminate

basics

~20 s

A bare throw; rethrows the same exception object with its full dynamic type. Writing throw e; copy-initializes a new exception object of e's static type, std::exception, so the derived type and its message are lost to outer handlers.

solid answer

~40 s

`throw;` creates no new object: it reactivates the currently handled exception, so an outer `catch (const ParseError&)` still matches and `what()` still returns the parser's message. `throw e;` is an ordinary throw-expression: the exception object's type comes from the *static* type of `e`, `std::exception`, and it is copy-initialized from the base part. Outer handlers for `ParseError` stop matching and, with libc++, `what()` returns `"std::exception"`. `throw;` executed when no exception is being handled calls `std::terminate`; that is a run-time event, not a compile error. When you want to add context instead of passing the error through, throw a new exception with `std::throw_with_nested` so the original travels inside it.

code

cpp · 28 lines
cpp
#include <iostream>
#include <stdexcept>

struct ParseError : std::runtime_error {
    using std::runtime_error::runtime_error;
};

void log_and_rethrow(bool copy) {
    try {
        throw ParseError("bad header");
    } catch (const std::exception& e) {
        std::cout << "logged: " << e.what() << '\n';
        if (copy) throw e;   // new object, static type std::exception
        throw;               // same object, dynamic type ParseError
    }
}

int main() {
    for (bool copy : {false, true}) {
        try {
            log_and_rethrow(copy);
        } catch (const ParseError& e) {
            std::cout << "caller sees ParseError: " << e.what() << '\n';
        } catch (const std::exception& e) {
            std::cout << "caller sees std::exception: " << e.what() << '\n';
        }
    }
}

go deeper

for a junior

Remember that a bare throw; passes the same exception on, while throw e; throws something new built from e.

for a middle

Explain that throw e; takes the exception object's type from e's static type and slices, and that throw; with nothing in flight calls std::terminate at run time.

for a senior

Use throw; in exception translation helpers and catch-all cleanup, and add context with std::throw_with_nested so reports keep the root cause.

for a principal

Decide where translation happens: one boundary layer that maps exceptions to error codes or messages, with nested exceptions carrying context, instead of ad hoc rethrows in every layer.

## Two expressions that look alike A C++ **throw-expression** has two forms, and the standard gives them different rules: - **With an operand** (`throw e;`): the operand's type, minus top-level cv-qualifiers, becomes the type of a **new exception object**, which is copy-initialized from the operand. - **Without an operand** (`throw;`): the **currently handled exception** is reactivated with the existing exception object; no new object is created. Inside `catch (const std::exception& e)` the static type of `e` is `const std::exception`, whatever was thrown. So `throw e;` creates a `std::exception` copied from the base subobject. The derived part is sliced off exactly as it would be by a by-value handler, and every outer handler now sees a plain `std::exception`. ## What the caller observes | Rethrow form | Exception object | Outer `catch (const ParseError&)` | `what()` in the caller | |---|---|---|---| | `throw;` | the original one | matches | the parser's message | | `throw e;` | a new `std::exception` | does not match | implementation-defined; libc++ gives `"std::exception"` | | `throw e;` where `e` is `const ParseError&` | a new `ParseError` copy | matches | same text, but a copy | The snippet below logs and rethrows both ways; the first loop iteration reaches the `ParseError` handler, the second reaches only the `std::exception` handler. ## When `throw;` is used 1. **Log and pass on.** A layer that cannot recover records the failure and rethrows without changing it. 2. **Partial cleanup in `catch (...)`.** A catch-all handler releases something that is not owned by an RAII object and then rethrows; it has no name for the exception, so `throw;` is the only way to pass it on. 3. **Exception translation functions.** A function called from inside a handler can write `try { throw; } catch (const ParseError& e) { ... } catch (const std::system_error& e) { ... }` to map whatever is in flight onto, say, an error code at an API boundary. This works because "currently handled" is a property of the thread, not of the lexical handler. ## The run-time trap `throw;` compiles anywhere. If it executes when no exception is being handled, for example because the translation function above was called outside a handler, the standard calls `std::terminate`. In a quick run with libc++ the program printed `libc++abi: terminating` and aborted. A `catch` block that has finished does not count: once the handler exits, the exception is no longer being handled. ## Adding context without losing the original Sometimes neither form fits: the importer wants to say *which file* failed while keeping the parser's own error. `<exception>` provides **nested exceptions** for that: - `std::throw_with_nested(std::runtime_error("importing " + path))` throws an object of an unspecified type derived from both `std::runtime_error` and `std::nested_exception`, and the `std::nested_exception` part captures the currently handled exception. - `std::rethrow_if_nested(e)` rethrows that captured exception if `e` carries one, so a reporter can walk the chain recursively. - `std::nested_exception::rethrow_nested()` on an object that captured nothing calls `std::terminate`. ```cpp void import_file(const std::string& path) { try { parse_all(path); } catch (...) { std::throw_with_nested(std::runtime_error("importing " + path)); } } ``` A reporter that catches `const std::exception&`, prints `what()` and calls `std::rethrow_if_nested` inside its own `try` prints the outer context first and the parser's message indented under it. ## Throwing a copy on purpose There are legitimate reasons to throw a *named* object, and they all differ from `throw e;` on a base reference: - **Throwing a local**: `ParseError err(msg, line); err.set_file(path); throw err;` builds the error step by step. The local is an automatic variable, so it is moved (or copied) into the exception object and its own lifetime does not matter. - **Rethrowing a modified exception**: catch by non-const reference, edit the object, then `throw;`. The edit is visible to outer handlers because the reference named the exception object itself. - **Throwing the derived type explicitly**: inside `catch (const ParseError& e)`, `throw e;` creates a new `ParseError`; nothing is sliced, but a copy is made and the original object is released when the handler exits. The defect is specific: an operand whose static type is a base of what was thrown. ## Review checklist - In a handler, write `throw;` unless you mean to throw a *different* exception. - Never write `throw e;` on a base-class reference; if you need a copy, name the derived type. - Keep translation functions private to the code that calls them from inside handlers. - To add context, nest; do not replace the original with a new message that drops it.

  • Can a function that is not itself a catch block use throw; legally?
    Yes. `throw;` rethrows the currently handled exception of the thread, so a helper called from inside a handler can rethrow and re-catch it, which is how exception translation functions map many exception types to one error code. The risk is calling the helper when nothing is being handled: then `throw;` calls `std::terminate` at run time, with no compile-time diagnostic.
  • How do you rethrow a captured exception after the handler has exited?
    Capture it inside the handler with `std::current_exception()`, which returns a `std::exception_ptr` that keeps the exception object alive. Later, possibly on another thread, `std::rethrow_exception(p)` throws it again; whether that throws the same object or a copy is unspecified. A bare `throw;` cannot do this, because after the handler exits no exception is being handled.
  • What does std::rethrow_if_nested do when the exception carries no nested exception?
    Nothing. It checks, with a `dynamic_cast` to `const std::nested_exception*`, whether the object has a `std::nested_exception` base; if the type is not polymorphic or has no such base, it simply returns. That makes it safe to call at every level of a recursive printer: the recursion stops at the innermost exception.

  • throw e; and throw; are equivalent because e is a reference to the exception.
  • throw; outside a catch block is a compile error.
  • throw e; preserves the dynamic type because what() is virtual.
  • To add context you must replace the original exception with a new message.