Listing 9 Illustrates the principle of "resource allocation is initialization"

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

void f(char *fname);

main()
{
   try
   {
      f("file1.dat");
   }
   catch(...)
   {
      puts("Exception caught in
          main()");
   }
   return 0;
{

void f(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
Exception caught in main()
*/

// End of File