Skip to main content

Section 10.7 Exceptions

Exceptions are a programming convention that allows a low-level function to communicate β€œthere was an error” to higher-level code that gets around some of the complications of other strategies..
When a function generates an exception, we say that it throws that exception. The thrown exception travels back up the call stack one function at a time, giving each higher-level function a chance to catch the exception.. If nothing catches the exception, the program will be stopped.
To start exploring exceptions, we will use a familiar string function. When 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:
Listing 10.7.1.
If you run that code, you should get an error like:
terminate called after throwing an instance of 'std::out_of_range'
An out_of_range exception was thrown by the attempt on line 80 to get the substring. Because the exception was not caught, the program was terminated.
Let’s try catching the exception in mediumJob. To catch an exception, we use this syntax:
Listing 10.7.2.
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 that is coming from somewhere else. Let’s add that to our program to catch the exception that is coming from substr:
Listing 10.7.3.
This time, we caught the exception. The exception happens on line 10. As soon as it happens, execution jumps to the catch. Line 11 never runs. Which is good, as there is no result from line 10 that it can use. Inside the catch, line 14 runs and prints a message. 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(?)").
That result is returned to bigJob in the normal manner and the program continues on as if nothing bad happened.

Note 10.7.1.

Every try MUST have a catch.
Execution in a try stops if an exception occurs, the rest of the try block will not get a chance to run.

Checkpoint 10.7.1.

Construct a try catch that attempts to call foo() and catches any errors that result.
You have attempted of activities on this page.