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
70 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
 Introduction
 Assertions
 Exceptions
 Return Values
 and Logging

 One More Thing...

 Printable version
 Discuss this article
 in the forums


Method 2 - Exceptions

Pros: Automatic cleanup and elegant shutdown, opportunity to continue if handled, works in both debug and release builds

Cons: Relatively slow

Explanation

Basically, you use the throw keyword to throw data up to some unknown function caller and the stack continues to unwind (think of it like the program is reversing itself) until someone catches the data. You use the try keyword to enclose code that you'd like to catch exceptions from. See:

void some_function() { throw 5; } // some function that throws an exception

int main(int argc, char* argv[])
{
  try // just letting the compiler know we want to catch any exceptions from this code
  {
    some_function();
  }

  catch(const int x) // if the type matches the data thrown, we execute this code
  {
    // do something about the exception...
  }
}

If you don't place try blocks in your code, then the stack will simply continue to unwind until it gets past the main function, and your program will exit. You don't have to place them everywhere - only where you can catch an exception and can recover from it. If you can only recover from it partially, you can rethrow the original exception (by the empty throw statement "throw;") and the stack will continue unwinding until it hits the next matching catch block.

Examples

Exceptions are best used in key places in debug and release builds to track exceptional conditions. If used properly, they provide automatic cleanup and then either force the application to quit or put itself back into a valid state. Thus exceptions are perfect for release code, because they provide everything the end user wants in a well-behaved program that encounters unexpected errors. Correctly used, they provide the following benefits:

  1. Automatic cleanup of all resources from any point in execution.
  2. They force the app to either quit or put itself back into a valid state.
  3. They force the recipient of the exception to handle it, instead of merely being optional (as with return values and assertions).
  4. They allow the deallocation code to be written by the person who wrote the allocation code and be handled implicitly (destructors, of course!).

Because of the overhead, it is generally a bad idea to use them for normal flow control because other control structures will be faster and more efficient.



Next : Return Values