Listing 5: Throws an exception in a constructor
// destroy7.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 x(fname,"r");
puts("Processing file...");
throw 2;
}
// Output:
Processing file...
File closed
Caught exception: 2
//End of File