Exceptions in C++
We have seen how C++ manages the local scope variables with automatic and dynamic lifetime. It calls the destructors of variables with an automatic lifetime when they go out of scope. We've also seen how raw pointers get destroyed when they go out of scope. As it does not clean up the dynamic lifetime variables, we lose them. This is a part of the story that builds us towards Resource Acquisition Is Initialization (RAII) later. But, first, we need to understand how exceptions change the flow of the program.
The Need for Exceptions
In Chapter 2A, No Ducks Allowed – Types and Deduction, we were introduced to enumerations as a way of dealing with magic numbers for the check_file() function:
FileCheckStatus check_file(const char* name)
{
FILE* fptr{fopen(name,"r")};
if ( fptr == nullptr)
return FileCheckStatus::NotFound;
char buffer[30];
auto numberRead = fread(buffer, 1, 30, fptr);
...