Listing 6: Reveals memory leak problems when using the new operator with exceptions
// destroy8.cpp #include <stdio.h> class File { FILE* f; public: File(const char* fname, const char* mode) { f = fopen(fname, mode); if (!f) throw 1; } ~File() { if (f) { fclose(f); puts("File closed"); } } }; main() { void f(const char*); try { f("file1.dat"); } catch(int x) { printf("Caught exception: %d\n",x); } } void f(const char* fname) { File* xp = new File(fname,"r"); puts("Processing file..."); throw 2; delete xp; // Won't happen } // Output: Processing file... Caught exception: 2 //End of File