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:
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:
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(?)").