IntroductionExceptions have been around in C++ for a while and are pretty common. If you use the STL or even just new you have been exposed to exceptions. Of course, like all things in C++, having a language feature does not necessarily clearly point one in the direction of the best use of that feature. I would not dare to call myself an expert or authority on exception handling, but as a user of C++ I've had some exposure to using exceptions. This article will offer some insight into the use and potential misuse of exceptions. I highly recommend reading Scott Meyer's More Effective C++; there is a whole section devoted to exceptions. Bjarne Stroustrup's The C++ Programming Language Third Edition also has some excellent information on exceptions. I am assuming that the reader is familiar with the basics of exception handling and hopefully has read over Meyer's items on exceptions. I also use a few terms from John Lakos's Large Scale C++ Software Design. This book is invaluable for understanding how a logical design should be translated into a collection of namespaces, header files, source files and libraries. I mostly refer to components and packages. Overview of C++ Exception HandlingC++ Exception Handling is centered around the three keywords: try, catch, and throw, the general purpose of which is to attempt to execute code and handle unexpected exceptional conditions, hence the name. This consists of utilizing a try block (with its attendant handlers). Here's a simple code snippet that should look familiar:
The code checks to see if a resource is available and if not, throws an exception. The handler for the MyExceptionClass presumably does something meaningful about the exceptional state. From this over-simplified example we can see a typical use of exceptions which is to prevent continued operation if the program cannot obtain the required resource. Another example of this use of exceptions is new(), which will throw the standard exception bad_alloc if the required amount of memory is not available. (Unless, of course, you've changed the new handler.) |
|||||||||||