FAQ 9.10 What is the best approach for the hierarchy of exception objects?

graphics/new_icon.gif

A monolithic hierarchy of exception classes works best.

Within the limited realm of exception classes, a singly rooted inheritance tree is superior to a forest of trees. This is an exception (pun intended) to the usual guideline that C++ class hierarchies should be a forest of trees.

One advantage of a monolithic hierarchy for exception classes is in catch-all situations. For example, main() often uses a try block that catches all possible exceptions. This catch-all block logs the uncaught exception and possibly restarts main(). This can be done via ellipses (catch (...)), but a monolithic hierarchy of exception classes allows main()'s catch clause to extract information from the exception object by means of member functions provided by the root class of the exception hierarchy. This allows a more detailed description of the unknown exception to be logged.

For example, suppose all exceptions are derived from the standard exception class called exception:

 #include <iostream> #include <exception> using namespace std; int main() {   try {                                                      <-- 1     return 0;   }   catch (const exception& e) {     // Oh No! somehow an exception leaked.     cerr << "uncaught exception: " << e.what() << '\n';   }   catch (...) {     cerr << "an exception didn't inherit from class  exception!\n"          << "contact the company at 1-800-BAD-BUGS\n";   }   return 1; } 

(1) The code that would normally go into main() goes here



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

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