Freebi32
Freebi32

Reputation: 23

C++ What is the standard way of doing cleanup after a exception have been caught?

So say I have a function that reads from a file. Something goes wrong while reading from the file and I catch an exception. The exception is not fatal; I can simply ask the user to enter a correct file. But in order to ask the user this I might have to exit the function that threw the exception. I was thinking about simply having a bool so it returns trueif all went well or false if something went wrong. Is this an accepted way of doing it or is there a standard for how it should be done?

A simple attempt to do it with RAII

#include <iostream>
#include <fstream>
class FileReader{
    std::ifstream file_descriptor;
public:
    FileReader();
    ~FileReader();
    void readFromFile();
};

FileReader::FileReader() :
        file_descriptor(std::ifstream("test.txt",std::ifstream::in)) {

}

FileReader::~FileReader() {
    file_descriptor.close();
}

void FileReader::readFromFile() {
    std::string line;
    while (std::getline(file_descriptor, line)){ //this can then be in a try block in case file reading goes wrong
        std::cout << line << std::endl;
    }
}

int main() {
    FileReader fileReader;
    fileReader.readFromFile();
    std::cout << "Hello, World!" << std::endl;
    return 0;
}

Is this what you guys mean? I do however feel I am violating the rule of three/five by having the destructor there. Or will the auto-generated destructor be enough?

Upvotes: 0

Views: 476

Answers (1)

eerorika
eerorika

Reputation: 238321

What is the standard way of doing cleanup after a exception have been caught?

The idiomatic way is to do the cleanup in the destructor.

For example, if you open a file, receiving a file descriptor (an integer value), you should do the opening in a constructor, store the descriptor in a member variable, and do the cleanup, including closing the file, in the destructor. This pattern is the RAII idiom.

Upvotes: 1

Related Questions