Handling Constructor Exceptions

How can I handle exceptions thrown in a constructor?

When an exception is thrown in a constructor, it cannot be caught within the constructor body itself. Instead, you need to use a function try block to catch the exception. Here's an example:

#include <iostream>
#include <stdexcept>

class MyClass {
 public:
  MyClass(int value) try : mValue{value} {
    if (value < 0) {
      throw std::invalid_argument{
        "Negative value"};
    }
  } catch (const std::exception& e) {
    std::cout << "Exception caught: "
      << e.what() << "\n";
    throw;  // Rethrow the exception
  }

 private:
  int mValue;
};

int main() {
  try {
    MyClass obj{-5};
  } catch (const std::exception& e) {
    std::cout << "Exception caught in main: "
      << e.what() << "\n";
  }
}
Exception caught: Negative value
Exception caught in main: Negative value

In this example, the constructor of MyClass uses a function try block to catch any exceptions thrown during the initialization of mValue. If an exception is caught, it is printed and then rethrown.

The exception is then caught in the main() function, where it can be handled appropriately.

Remember, when an exception is caught in a constructor's function try block, it must be rethrown or replaced with another exception. It cannot be fully handled within the catch block itself.

Function Try Blocks

Learn about Function Try Blocks, and their importance in managing exceptions in constructors

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Multiple Catch Blocks in Function Try Blocks
Can I have multiple catch blocks in a function try block?
Return Types in Function Try Blocks
How do I specify a return type for a function that uses a function try block?
Function Try Block vs Regular Try-Catch
When should I use a function try block instead of a regular try-catch block?
Rethrowing Exceptions
What happens if I don't rethrow an exception caught in a function try block?
Catching All Exceptions
How can I catch all exceptions in a function try block?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant