Listing 2: Deallocates a resource in the midst of handling an exception

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

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

void f(const char* fname)
{
    FILE* fp = fopen(fname,"r");
    if (fp)
    {
        try
        {
            throw 1;
        }
        catch(int)
        {
            fclose(fp);
            puts("File closed");
            throw;  // Re-throw
        }

        fclose(fp); // The normal close
    }
}

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