liveBook · Manning

Catch by reference

As explained in 100 C++ Mistakes and How to Avoid Them

Catch by reference is the C++ exception-handling technique of binding a handler parameter to the thrown exception through a reference.

Catch exceptions by reference after throwing them by value. Binding the handler to the thrown object avoids a second copy and preserves polymorphic behavior, so an overridden derived exception method remains available. section 10.9

The safer handler

Throw a DerivedException by value, then catch it as `const std::exception&`. The temporary created at the throw site is transferred to the handler by reference. By contrast, catching by value creates another copy and can lose derived-class behavior; throwing pointers introduces deletion and lifetime hazards. section 10.9

Listing 10.18 Catching an exception by reference
struct DerivedException : public std::exception {
    std::string message;
    DerivedException() : message("DerivedException") {}
    ~DerivedException() throw() {}
    const char* what() const throw() { return message.c_str(); }
};
 
void throw_by_value_catch_by_reference() {
    DerivedException de;
    throw de;                                                 #1
}
 
int main() {
    try {
        throw_by_value_catch_by_reference();
    } catch(const std::exception& ex) {                       #2
        std::cout << ex.what() << '\n';
    }
    return 0;
}

A complete C++ example contrasts value throwing with a const-reference handler and calls the derived exception's `what()` method. section 10.9

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Explains copy counts, temporary binding, polymorphism, and pointer hazards, stopping short of broader exception design.
Examples
Uses DerivedException examples contrasting local-pointer, heap-pointer, value, and const-reference catches.
What you can do after
Apply exception handling by throwing values and catching const references to reduce copying and preserve polymorphism.
How it connects
Connects exception handling with polymorphism, object copying, pointers, references, and local-object lifetime.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.