skip to content

In C++, why is the rule to throw exceptions by value and catch them by const reference rather than by value?

level: juniorimportance: must knowfreq 75%

answer

  1. who owns the exception object
  2. a copy of the base part
  3. what() of the dynamic type
  4. slicing in the handler parameter

basics

~20 s

Throwing by value lets the runtime own the exception object. A const reference handler binds to that object, so a derived exception keeps its type and message; a by-value handler copies only the named base, slicing the rest away.

solid answer

~40 s

`throw ParseError(...)` copy-initializes an exception object that the runtime keeps alive until the last handler is done, so nobody has to `delete` it. A handler `catch (const std::exception& e)` binds `e` to the base subobject of that very object, so the virtual `what()` still reaches `ParseError`'s message and a later `throw;` still carries a `ParseError`. A handler `catch (std::exception e)` copy-initializes a new `std::exception` from the base part: the derived members and override are sliced away, and if that copy itself throws, `std::terminate` is called. `const` documents that the handler only reads it; a non-const reference is for a handler that deliberately edits the object before rethrowing.

code

cpp · 22 lines
cpp
#include <iostream>
#include <stdexcept>
#include <string>

struct ParseError : std::runtime_error {
    int line;
    ParseError(const std::string& msg, int l)
        : std::runtime_error(msg), line(l) {}
};

void parse() { throw ParseError("unexpected token", 42); }

int main() {
    try { parse(); }
    catch (std::exception e) {               // by value: copies the base subobject
        std::cout << "by value: " << e.what() << '\n';
    }
    try { parse(); }
    catch (const std::exception& e) {        // by reference: the original object
        std::cout << "by ref:   " << e.what() << '\n';
    }
}

go deeper

for a junior

Recall the pairing: throw a temporary of a class type, catch it as a const reference, and explain that a by-value handler slices a derived exception down to its base.

for a middle

Explain that the handler parameter is copy-initialized from the exception object, why that copy is a base slice, and why a copy that throws at that moment ends in std::terminate.

for a senior

Show you police this in review: GCC flags it under -Wall while clang with -Wall -Wextra stayed silent, private bases escape handlers, and pointers to heap exceptions leak on some path.

for a principal

Frame the convention as part of a team's exception-type policy: one public hierarchy rooted in std::exception, cheap noexcept copies, and handler style enforced by tooling rather than by memory.

## What a throw-expression creates In C++, `throw expr;` does not throw the expression itself. It **copy-initializes an exception object** from the operand, with the operand's type minus top-level `const`, and the runtime stores that object in memory it manages. The object lives until the last handler that refers to it exits without rethrowing (or until the last `std::exception_ptr` that refers to it is gone). That is why the idiom is **throw by value**: - `throw ParseError("unexpected token", 42);` gives the runtime a complete `ParseError`. - `throw new ParseError(...)` throws a *pointer*: only a `catch (ParseError*)` or `catch (const ParseError*)` handler matches it, and somebody has to remember to `delete` it, on every path. - Throwing a local by name (`throw err;`) copies or moves `err` into the exception object, so the local's lifetime does not matter. ## How a handler's parameter is initialized The standard says the handler's variable is **copy-initialized** from the exception object. If the handler type is a public base `T` of the thrown type `E`, the copy is made from the `T` base subobject. That single rule explains both forms: | Handler | What `e` is | Dynamic type seen through `e` | |---|---|---| | `catch (std::exception e)` | a new `std::exception` copied from the base part | `std::exception` | | `catch (const std::exception& e)` | a reference to the exception object itself | the thrown type, e.g. `ParseError` | With the reference, `e.what()` is a virtual call on the real object, so it returns the derived message. With the value, the virtual call is made on a genuine `std::exception`, and `std::exception::what()` returns an implementation-defined string; libc++ returns `"std::exception"`. The derived members, such as a line number, are gone. This is **slicing**, the same rule that slices any polymorphic object passed by value. ## Two more costs of catching by value 1. **The copy can fail.** Copying the exception into the handler parameter happens after the exception object exists but before the handler is active. If a copy constructor exits via an exception at that point, the standard calls `std::terminate`. A custom exception holding a `std::string` can throw `std::bad_alloc` while being copied. 2. **Rethrowing still works, but edits are lost.** `throw;` inside a by-value handler rethrows the original object, not the copy, so changes made to the parameter vanish. With a non-const reference, changes are made to the exception object itself and later handlers see them. ## Matching rules that surprise people A handler matches when its type is the thrown type, or an **unambiguous public base** of it, or (for pointers) a type reachable by a standard pointer or qualification conversion. Consequences: - A class that inherits *privately* from `std::exception` is **not** caught by `catch (const std::exception&)`. - No user-defined or arithmetic conversion applies: `throw 42;` does not match `catch (long)`, and `throw "text";` throws a `const char*` that `catch (const std::string&)` never sees. - `const` on the reference costs nothing and documents that the handler only reads the exception object. ## What the compilers tell you GCC's `-Wcatch-value` warns about polymorphic class types caught by value, and its manual lists it as enabled by `-Wall`. Apple clang 21, run with `-Wall -Wextra` on the snippet below, compiled `catch (std::exception e)` without a warning, so on clang the rule rests on review and on static analysis rather than on the default warning set. ## Designing exception types that are cheap to catch The standard requires every standard library class derived from `std::exception` to have a public copy constructor and copy assignment operator with a **non-throwing exception specification**, and a copy must return the same `what()` text. Your own exception types should follow the same contract, because the runtime may copy them (into the exception object, into `std::exception_ptr` storage, or into a by-value handler): - Derive from `std::runtime_error` or `std::logic_error` and pass the message to the base constructor, so the base stores it; libstdc++ and libc++ both keep it in a reference-counted buffer, which is why copying their exceptions does not allocate. - Keep extra members small and cheaply copyable: a line number, an error code, not a `std::vector` of diagnostics. - Override `what()` only if you must, mark it `noexcept`, and return a pointer whose lifetime matches the exception object. ## A checklist for handlers - Throw a class type derived publicly from `std::exception` (often `std::runtime_error` or `std::logic_error`), by value. - Catch it as `const T&`; drop `const` only to annotate the object before `throw;`. - Never throw a pointer to a heap object. - Order handlers most-derived first, which is the subject of handler ordering.

  • Why does an exception class that inherits privately from std::exception escape a catch (const std::exception&) handler?
    A handler of type `T` or `T&` matches only when `T` is the thrown type or an *unambiguous public* base of it. Private (or protected) inheritance hides the base, and so does inheriting `std::exception` twice through two paths, which makes it ambiguous. The search moves on to outer handlers and, if none matches, ends in `std::terminate`. Exception hierarchies should derive publicly and, with multiple inheritance, virtually from `std::exception`.
  • When does catching by non-const reference make sense?
    When the handler adds context to the exception object and then rethrows it with `throw;`. Because the reference names the exception object itself, a later handler sees the change, for example a file name appended to a member of a custom exception. A by-value parameter would be edited and then discarded, since `throw;` rethrows the original object and not the handler's copy.

Catching by value is like photocopying only the cover page of a multi-page incident report: the copy is a real document, but every detail the later pages carried is gone, and whoever reads the copy cannot tell what kind of incident it was.

  • Catching std::exception by value is fine because what() is virtual.
  • Throwing new and catching a pointer avoids copying, so it is the efficient form.
  • A by-value handler and a by-reference handler see the same object.
  • Inheriting privately from std::exception still lets catch (const std::exception&) match.
  • A handler for std::string catches a thrown string literal.