FAQ 9.02 How should runtime errors be handled in C?

FAQ 9.02 How should runtime errors be handled in C++?

graphics/new_icon.gif

Use C++ exceptions.

The purpose of the C++ exception-handling mechanism is to handle errors in software composed of independently developed components operating in a single process and under synchronous control.

In C++, a routine that cannot fulfill its promises should throw an exception. The caller that knows how to handle this unusual situation can catch the thrown exception. Callers can specify the types of exceptions they are willing to handle; exceptions that don't match the specified types are automatically propagated to the caller's caller. Thus intermediate callers (between the thrower and the catcher) can simply ignore the exception. Only the original thrower and the ultimate catcher need to know about the unusual situation.

This is illustrated in the following call graph. In the diagram, main() calls f(), which calls g(), and so forth. Typically these routines are member functions on objects, but they may also be non-member ("top-level") functions. Eventually routine i() detects an erroneous situation such as an invalid parameter, an invalid return value from another object, an invalid entry in a file, a network outage, or insufficient memory, and i() throws an exception. The thrown exception is caught by f(), meaning control is transferred from i() to f(). Routines g(), h(), and i() are removed from the runtime stack and their local variables are destructed.

The effect is to separate policy from mechanism. Objects at low levels (such as i()) have the mechanism to detect and throw exceptions, and objects at higher levels, such as f(), specify the policy of how exceptions are to be handled.

graphics/09fig01.gif



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