Upcoming Events
Unite 2010
11/10 - 11/12 @ Montréal, Canada

GDC China
12/5 - 12/7 @ Shanghai, China

Asia Game Show 2010
12/24 - 12/27  

GDC 2011
2/28 - 3/4 @ San Francisco, CA

More events...
Quick Stats
89 people currently visiting GDNet.
2406 articles in the reference section.

Help us fight cancer!
Join SETI Team GDNet!
Link to us Events 4 Gamers
Intel sponsors gamedev.net search:

  Contents

 Overview
 Implications
 Specifications
 Designing With
 Exceptions

 Resources
 Interactions With
 Threads

 Real-Time Systems
 Philosophies
 Potential Pitfalls

 Printable version

 


Introduction

Exceptions 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 Handling

C++ 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:

try { if ( ! resourceAvail ) throw MyExceptionClass( "Resource Is Not Available" ); } catch(MyExceptionClass& myException) { // resource was not available, do something cleanup throw; }

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.)





Next : Implications of Using Exceptions