Skip to content

Trivia impact: rare

The Constructor That Catches and Still Fails

the handler runs, yet no Meter object reaches the caller

struct Meter {
  Meter() try : value(load()) {
    std::cout << "body\n";
  } catch (...) {
    std::cout << "handler\n";
  }

  int value;
  static int load() { throw 1; }
};

try {
  Meter meter;
} catch (...) {
  std::cout << "caller\n";
}

Can a constructor catch a failed member initializer and return normally?

Answer
handler
caller

The constructor's handler runs, then the original exception reaches the caller.

Why

A constructor function-try-block covers its member initializers, so the exception from load() enters the handler before the body executes. [except.ctor] says that if a constructor handler reaches its end, the exception is rethrown automatically. Thus body never prints and no partially initialized Meter object is produced.

Where it shows up

This form is occasionally useful for logging or translating failures during construction. It cannot make an object usable after a base or member initializer has failed.

Takeaway: A constructor function-try-block may observe initialization failure, not recover an object.

Try it: g++ -std=c++17 main.cpp -o demo && ./demo

Open in Compiler Explorer ↗ Quiz this entry