Junior — Middle
What are the consequences if an unhandled exception occurs in the constructor of an object?
sobes.tech AI
Answer from AI
If an unhandled exception occurs in a constructor of an object in C++, then:
- The constructor is considered to have not completed successfully, and the object is not created.
- Destructors are called for all already created members of the object (for example, fields that were initialized before the exception occurred).
- Memory allocated for the object is automatically released.
- The exception is propagated further up the call stack if not caught within the constructor.
This prevents the creation of partially initialized objects and ensures resource safety.
Example:
class MyClass {
public:
MyClass() {
// Initialization
throw std::runtime_error("Error in constructor");
}
};
int main() {
try {
MyClass obj;
} catch (const std::exception& e) {
std::cout << "Caught exception: " << e.what() << std::endl;
}
}