Exceptions
Exceptions in C++ are error-handling mechanisms that are based on the principle of throwing and catching objects of an arbitrary type. All exceptions that are thrown from the standard library derive from the std::exception class defined in the <exception> header. We put code that may throw an exception in the try block, and we define the type of exception we want to catch in the catch clause, as shown in the following example:
std::array<int, 4> arr;
try {
arr.at(5) = 6;
}
catch(std::out_of_range &e) {
printf("Array out of range!\r\n");
}
In the preceding example, we have defined std::array arr, an array of integers with four members. In the try block, we are trying to access an element with index 5, which is clearly out of the defined range, and the at method will throw the std::out_of_range exception. In order to run this example, go to the Chapter07/error_handling folder, make sure that the build folder...