Note 10.7.1.
For reasons we are ready to go into, we need to catch exceptions by reference rather than by value. We will never write
catch(const exception e).
substr is given a bad index it responds by throwing an exception. Try running this sample that ends up asking for a substring starting at index 50 in a much shorter string:
terminate called after throwing an instance of 'std::out_of_range'
out_of_range exception was thrown by the attempt on line 8 to get the substring. Because the exception was not caught, the program was terminated.
mediumJob. To catch an exception, we use this syntax:
try {
// code that might throw an exception
} catch (const exception& e) {
// code to handle the exception
}
exception is a data type defined in the <exception> library. catch(const exception& e) says that the variable e is going to be a const reference to an exception.
catch(const exception e).
substr:
catch. Line 12 never runs. Which is good, as there is no result from line 11 that it can use!
e.what() results in a string that describes the exception. The code then recovers from the error by setting the mediumResult variable to a default value ("mediumJob(?)").
bigJob in the normal manner and the program continues on as if nothing bad happened.
try MUST have a catch.
try stops if an exception occurs, the rest of the try block will not get a chance to run.
foo() and catches any errors that result.