Sobes.tech
Junior — Middle

How do exceptions work during constructor execution and what should be known about them?

sobes.tech AI

Answer from AI

If an exception occurs during the execution of a constructor in C++, then:

  • The constructor is considered to have not completed successfully, and the object is not created.
  • Destructors are called for already constructed members of the object in reverse order of their initialization.
  • The memory allocated for the object is automatically released.

It is important to remember:

  • Exceptions in the constructor should be handled or propagated upwards to avoid undefined behavior.
  • If the constructor throws an exception, destructors for the object are not called, as the object is not considered to have been created.
  • Exceptions in the initializer list of the constructor also lead to the cancellation of object creation.

Example:

class Example {
public:
    Example() {
        // If an exception is thrown here, the object is not created
        throw std::runtime_error("Error in constructor");
    }
};

int main() {
    try {
        Example ex;
    } catch (const std::exception& e) {
        std::cout << "Caught exception: " << e.what() << std::endl;
    }
}

In this example, the object ex will not be created, and the exception will be handled in the catch block.

How do exceptions work during constructor execution… - sobes.tech