How to return error code from constructor?

vanta mula picture vanta mula · Aug 11, 2017 · Viewed 10.4k times · Source

I am trying to return error code from constructor, since constructor does not return an error code, I tried to put an exception on the constructor. Then in the catch block I return my appropriate error code. Is this a proper way of returning error code from constructor ?

#include <exception>
#include <iostream>

class A {
 public:
  A() { throw std::runtime_error("failed to construct"); }
};

int main() {
  try {
    A a;
  } catch (const std::exception& e) {
    std::cout << "returining error 1 \n";
    return 1;
  }

  return 0;
}

Answer

HatsuPointerKun picture HatsuPointerKun · Aug 11, 2017

According to isocpp.org, the proper way to handle the failure in a constructor in C++ is to :

Throw an exception.

It's not possible to use error code since constructors don't have return types. But :

If you don’t have the option of using exceptions, the “least bad” work-around is to put the object into a “zombie” state by setting an internal status bit so the object acts sort of like it’s dead even though it is technically still alive.

But you should really use exceptions to signal failure in constructors if you can, as said :

In practice the “zombie” thing gets pretty ugly. Certainly you should prefer exceptions over zombie objects, but if you do not have the option of using exceptions, zombie objects might be the “least bad” alternative.