Andrew Sun Andrew Sun - 4 months ago 7
C++ Question

How to catch a constructor exception?

I have a C++ class which throws an exception from the constructor on failure. How can I allocate a local instance of this class (without using

new
) and handle any possible exceptions, while keeping the
try
block scope as small as possible?

Essentially, I am looking for the C++ equivalent of the following Java idiom:

boolean foo() {
Bar x;
try {
x = new Bar();
} catch (Exception e) {
return false;
}
x.doSomething();
return true;
}


I do not want to catch exceptions from
x.doSomething()
, only the constructor.

I suppose what I'm looking for is a way to separate the declaration and the initialization of
x
.

Is it possible to accomplish this without using heap allocations and pointers?

Answer

You can use std::optional from C++17:

bool foo() {
    std::optional<Bar> x;
    try {
        x.emplace();  // construct Bar via default constructor
    } catch (const Exception& e) {
        return false;
    }
    x->doSomething();
    return true;
}