liveBook · Manning

Throw by value

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

Throw by value is the C++ exception-handling technique of throwing an exception object as a value rather than as a pointer or reference.

Choosing pointer throws to minimize transferred data is a misleading optimization: C++ copies whatever is thrown, including a pointer. Prefer throwing an exception object by value and catching it by reference. section 10.9

Listing 10.17 Catching an exception by pointer and value
struct DerivedException : public std::exception {
    std::string message;
    DerivedException() : message("DerivedException") {}
    ~DerivedException() throw() {}
    const char* what() const throw() { return message.c_str(); } #1
};
 
void throw_by_local_pointer() {
    DerivedException de;
    throw &de;
}
 
void throw_by_heap_pointer() {
    DerivedException* de = new DerivedException();
    throw de;
}
 
void throw_by_value() {
    DerivedException de;
    throw de;
}
 
int main() {
    try {
        throw_by_local_pointer();
    } catch(std::exception* ex) {
        std::cout << ex->what() << '\n';
    }
    try {
        throw_by_heap_pointer();
    } catch(std::exception* ex) {
        std::cout << ex->what() << '\n';
    }
    try {
        throw_by_value();
    } catch(std::exception ex) {
        std::cout << ex.what() << '\n';
    }
    return 0;
}

Compare local-pointer, heap-pointer, and value throws alongside their catch forms. section 10.9

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

How deep it goes
Works through a constructor-count experiment and explains that C++ copies the thrown object or pointer.
Examples
Compares local-pointer, heap-pointer, and value throws, then shows a value throw caught by const reference.
What you can do after
Apply the pattern by throwing an exception object by value and catching it by const reference.
How it connects
Connects exception handling with object copying and reference catches.

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.