Listing 3: Illustrates the principle of "Resource Allocation is Initialization"

// destroy5.cpp
#include <stdio.h>

main()
{
    void f(const char*);
    try
    {
        f("file1.dat");
    }
    catch(int)
    {
        puts("Caught exception");
    }
}

void f(const char* fname)
{
    class File
    {
        FILE* f;
    public:
        File(const char* fname,
             const char* mode)
        {
            f = fopen(fname, mode);
        }
        ~File()
        {
            fclose(f);
            puts("File closed");
        }
    };

    File x(fname,"r");
    throw 1;
}

// Output:
File closed
Caught exception
//End of File