Middle+
What should be remembered when throwing exceptions in a constructor?
sobes.tech AI
Answer from AI
When throwing an exception in a constructor, the following should be remembered:
- Partially constructed object: If an exception is thrown before the initialization of all class members is complete, the object is considered partially constructed. Its destructor will not be called.
- Resource release: Resources acquired before the exception is thrown (for example, memory allocated in constructors of initialized members) must be explicitly released. The RAII (Resource Acquisition Is Initialization) idiom is an ideal solution for automatic resource management in such cases.
- Absence of destructor: Since the destructor is not called, code that relies on the destructor for cleanup (such as freeing memory, closing files) will not execute.
- Resource leaks: Without proper care for releasing resources when an exception is thrown in a constructor, memory leaks, file descriptor leaks, and other resource leaks can occur.
Example of using RAII to prevent leaks:
#include <iostream>
#include <memory> // for std::unique_ptr
class Resource {
public:
Resource() { std::cout << "Resource acquired\n"; }
~Resource() { std::cout << "Resource released\n"; }
};
class MyClass {
private:
std::unique_ptr<Resource> res; // Using RAII (unique_ptr)
public:
MyClass() : res(std::make_unique<Resource>()) {
std::cout << "MyClass constructor starts\n";
// Suppose something here can throw an exception
if (true) { // Simulating a condition to throw an exception
throw std::runtime_error("Error during construction");
}
std::cout << "MyClass constructor finishes\n";
}
~MyClass() {
std::cout << "MyClass destructor\n";
}
};
int main() {
try {
MyClass obj;
} catch (const std::exception& e) {
std::cerr << "Caught exception: " << e.what() << std::endl;
}
return 0;
}
In this example, std::unique_ptr owns the Resource. If an exception is thrown in the MyClass constructor after res has been initialized, the destructor of std::unique_ptr will be called automatically, ensuring the resource Resource is released.