PreludeNo, 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 p->Some_Method(); 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. |