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.
Answers to questions are automatically generated and may not have been reviewed.
Learn about Function Try Blocks, and their importance in managing exceptions in constructors