Andrew Sun Andrew Sun - 1 year ago 130
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

) and handle any possible exceptions, while keeping the
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;
return true;

I do not want to catch exceptions from
, only the constructor.

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

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

Answer Source

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;
    return true;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download