2

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.

Piotr Skotnicki
  • 46,953
  • 7
  • 118
  • 160
DerWolferl
  • 71
  • 7
  • RAII only work with exceptions if you handle those exceptions. In your case you do not, so once the exception causes `main` to exit, `std::abort` is called and the program is immediately terminated. No stack unwinding happens and that means your object is not destroyed. – NathanOliver Jun 09 '20 at 15:55
  • @NathanOliver It's implementation-defined if stack unwinding happens here or not. – HolyBlackCat Jun 09 '20 at 15:56
  • @DerWolferl `catch` the exception, then the destructor will be called. Also, I'm not sure if it's intentional or not (for brevity), but your code doesn't follow [the rule of three](https://en.cppreference.com/w/cpp/language/rule_of_three). – HolyBlackCat Jun 09 '20 at 15:57
  • @HolyBlackCat Thank you, that makes sense, so RAII only helps me in a way, that I dont have to remeber to write fclose() in every catch-Block where I use my File resource? – DerWolferl Jun 09 '20 at 16:16
  • Yes, what else could it do? – HolyBlackCat Jun 09 '20 at 16:35

0 Answers0