Up to this point in the chapter, we have handled all the exceptions the same way. This is quick and easy, but not always the best method. Think about it this way—different errors will require different handling. If the error is a “file not found,” then you probably want to prompt the user to enter a different file name. If the error is a division by 0 error, then you probably want to prompt the user to enter a non-0 number. Some functions of the standard C++ language library send exceptions that can be captured if we include them within a try block. These exceptions are sent with a class derived from std::exception as type. Each exception has a specific class associated with it. This class (std::exception) is defined in the C++ standard header file <exception> and serves as pattern for the standard hierarchy of exceptions. Again for now you should simply think of a class as a bag of functions. (Classes will be discussed soon!) Figure 7.2 summarizes some of the more commonly encountered exception classes.
Figure 7.2: Exception classes.
Microsoft defines its own set of exception classes for use with Visual C++, however, the standard exception classes will work with Visual C++ and with all other C++ compilers.
The hierarchy you see demonstrated in Figure 7.2 is not exhaustive. It does, however, show you the relationship between exceptions. This becomes important when you are handling multiple exceptions. You can trap specific errors and handle them differently. You must remember that you have to trap exceptions in the reverse order of how they appear on the hierarchy. What this means is that if you trap run_time_error you cannot then have another catch statement for FileAccessError after that. The reason is that the exception higher up in the hierarchy includes all lower exceptions that come under it in the hierarchy. Put another way, you should trap the most specific and, therefore, lower-level exceptions first, then work your way toward more general exceptions.
Once we move forward into classes and object-oriented programming, you will learn how to create your own exception objects.