Exception Classes


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.

click to expand
Figure 7.2: Exception classes.

Hint!

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.




C++ Programming Fundamentals
C++ Programming Fundamentals (Cyberrookies)
ISBN: 1584502371
EAN: 2147483647
Year: 2005
Pages: 197
Authors: Chuck Easttom

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net