I have a class whose constructor may throw an exception. Here’s some code that will catch the exception:
try {
MyClass instance(3, 4, 5);
}
catch (MyClas
A variant of Remy's answer, but saving a dynamic allocation using std::optional
:
std::optional instance_opt;
try {
// could use `instance = MyClass(3, 4, 5)`, but that requires you to write a move constructor
instance_opt.emplace(3, 4, 5);
}
catch (const MyClassException& ex) {
std::cerr << "There was an error creating the MyClass." << std::endl;
return 1;
}
MyClass& instance = *instance_opt;
// use instance as needed...