Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return error code from constructor?

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;
}
like image 866
vanta mula Avatar asked Aug 11 '17 21:08

vanta mula


1 Answers

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.

like image 82
HatsuPointerKun Avatar answered Oct 10 '22 16:10

HatsuPointerKun