Function Try Blocks

Handling Constructor Exceptions

How can I handle exceptions thrown in a constructor?

Abstract art representing computer programming

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.

This Question is from the Lesson:

Function Try Blocks

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

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Function Try Blocks

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

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved