Sobes.tech
Middle

What needs to be done to throw exceptions from a constructor?

sobes.tech AI

Answer from AI

No special action is needed to throw an exception from a constructor. The standard throw mechanism works in constructors just as it does in regular functions.

When an exception is thrown from a constructor:

  1. Objects initialized before the throw point will be destroyed in the reverse order of their creation.
  2. Members of the object initialized before the throw point will be destroyed.
  3. Base classes that were successfully initialized will be properly destroyed.
  4. Memory allocated for the object will be freed (if the object was created dynamically using new).
  5. The object itself is considered improperly constructed, and its destructor will not be called if the exception was thrown before the constructor completed.

Example:

#include <stdexcept> // For std::runtime_error
#include <iostream>

class MyClass {
public:
    int value_;

    MyClass(int val) : value_(val) {
        std::cout << "Constructor called for MyClass with value: " << value_ << std::endl;
        if (value_ < 0) {
            throw std::runtime_error("Value cannot be negative"); // Throw an exception
        }
    }

    ~MyClass() {
        std::cout << "Destructor called for MyClass with value: " << value_ << std::endl;
        // Destructor will not be called if the constructor did not complete successfully
    }
};

int main() {
    try {
        MyClass obj1(10); // Successfully constructed
        // Further actions with obj1
        MyClass obj2(-5); // Throws an exception
        // This code will never be executed
    } catch (const std::runtime_error& e) {
        std::cerr << "Caught exception: " << e.what() << std::endl;
    }

    return 0;
}