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
