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
