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
65 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:

 What are

 Exception Safety
 and Error Handling

 Exception Class
 Final Thoughts

 Printable version
 Discuss this article
 in the forums


No, there aren’t any damsels to save or dragons to fight here. Our insidious foe comes in different guises on different operating systems - General Protection Fault, Illegal Operation, Segmentation Fault...

Our defense: Exceptions.

This document presents error-handling strategies using exceptions and how to write robust code. Code that works is good, and code that doesn’t should leave the system in the state it was before the program started. That is code robustness, and exceptions are designed exactly for such purposes.

Though C++ exceptions are platform independent, the discussion here tends towards the Windows platform.

If you feel a need to contact me, mail me at robin@cyberversion.com

Why bother with Exceptions?

Take a look at this code fragment

int main()
  Object *p = new Object();      // assume Object is a defined class


  delete p;

  return 1;

At first glance, there is nothing wrong with the code. After all, most C++ books have code like that. However, the above code is not robust. What if the Some_Method() function generates an error that would crash the program? Then delete p would never be called and the memory would not be freed. This is a common situation known as a memory leak.

In C++, there isn’t a garbage collector like other languages, and most people would say that is a serious flaw in C++. I used to think like that too, until I learned about exceptions.

Next : What are Exceptions?