TITLE: elementary exception cleanup (Newsgroups: comp.lang.c++.moderated, 5 Nov 99) MATHIASEN: "Daniel W. Mathiasen" > You can't do this in C++: > > try > { > int* i = new int; > > // Some code > } > catch (CException* e) > { > > // Handle exception > > } > finally > { > delete i; > > // make sure every resource gets freeA?d up. > } > > What can I do to archive the same thing...? STROUSTRUP: Bjarne Stroustrup , http://www.research.att.com/~bs That's very ugly code with ad hoc error handling. I consider that style error-prone. Fortunately, we can do much better. Consider first a small program: #include #include using namespace std; int main() { auto_ptr p(new int); *p = 7; cout << *p << endl; return 0; } Here, the standard library type auto_ptr ensures that the new int is automatically destroyed at the end of the function. This is a general method of cleaning up resources without explicit error handling code. There is no particular magic in auto_ptr. It is simply a handle to the object it is initialized with and it has a destructor that deletes that object. Consider a slightly more elaborate example: #include #include using namespace std; class X { public: X() { cout << "make X\n"; } ~X() { cout << "destroy X\n"; } }; int main() { auto_ptr p(new int); auto_ptr px(new X); *p = 7; cout << *p << endl; return 0; } The general idea of relying on destructors to guarantee cleanup in the presence of exceptions is called "resource acquisition is initialization". Look it up in some C++ textbook. It is very clean and general. Naturally, this works even if you need to write some explicit error handling code. For example: int main() { try { auto_ptr p(new int); auto_ptr px(new X); *p = 7; cout << *p << endl; // ... } catch(Some_exception e) { // handle e } return 0; } or int main() { auto_ptr p(new int); auto_ptr px(new X); try { *p = 7; cout << *p << endl; // ... } catch(Some_exception e) { // handle e } return 0; } In either case, the all resources successfully acquired are properly released. Often, a cleaner version is to use automatic objects rather than objects on the free store. For example: int main() { int i; X x; i = 7; cout << i << endl; return 0; }