Catch by value
catch (runtime_error e)
versus catch by reference
catch (runtime_error& e)
You'd use the later when you have (usualy polymorphic) exception class hierarchy and you want to catch exceptions of all the derived types in a single catch clause.
For example, all the exception classes from the standard library derive from std::exception
, so you can do something like this:
try {
int i;
std::cin >> i;
switch (i) {
case 1: throw std::range_error();
case 2: throw std::overflow_error();
case 3: throw std::undefflow_error();
default: throw std::logic_error();
}
} catch (std::exception& e) {
// handle all the exceptions the same way,
// but print a diagnostic message polimorphicaly
std::cout << "I caught: " << e.what() << '\n';
}
If, instead by reference, you'd catch by value, you'd always catch a std::exception
, sliced off of the derived part of the object.