Sobes.tech
Junior — Middle

What points should be considered when throwing an exception inside a class constructor?

sobes.tech AI

Answer from AI

When throwing an exception inside a class constructor in C++, the following points should be considered:

  • If an exception is thrown, the object is considered not created, and its destructor is not called.
  • All members of the object that were successfully initialized before the exception will be properly destroyed.
  • Be cautious with resources allocated before the exception is thrown to avoid memory leaks.
  • It is recommended to use RAII (Resource Acquisition Is Initialization) — encapsulate resources in objects that manage their own cleanup.

Example:

class FileWrapper {
    FILE* file;
public:
    FileWrapper(const char* filename) {
        file = fopen(filename, "r");
        if (!file) {
            throw std::runtime_error("Failed to open file");
        }
    }
    ~FileWrapper() {
        if (file) fclose(file);
    }
};

Here, if fopen fails, an exception will be thrown, and the object will not be created, thus preventing resource leaks.