I've read about RAII a bit in the last few days and I always thought that I understood it. So I just wanted to write a little program that has an Object that handles a file and wanted to try RAII with throwing an exception. Here is what I did:
using namespace std;
class FileHandler{
FILE* file;
public:
FileHandler(const string &s, const char *r){
cout << "opened file";
file = fopen(s.c_str(), r);
fputs("test", file);
}
~FileHandler(){
cout << "closed file";
fclose(file);
}
};
#include "FileHandler.h"
#include <stdexcept>
int main() {
FileHandler fileHandler("test.txt", "w");
throw std::invalid_argument("why does this not work?");
}
From what I know about RAII the Destructor of FileHandler should be called and I should have an output on my console but somehow I don't get any output except the output for the exception. Does the exception output override my cout output or is my understanding of RAII wrong. I wanted to use this code to demonstrate to somebody else how RAII works, which is not really helpfull when I dont have the expected console output.
Thanks for any help.