Search code examples
c++exceptionthrow

Can a constructor for an object to be thrown throw an exception?


In C++, is it valid for the constructor of an object that is going to be thrown itself throw an exception? In other words, are we in the throw yet while we are still constructing the object to throw?

struct Error {
  Error() {
    if (someCondition()) {
      throw anotherObject();
    }
  }
};

void test() {
  throw Error();
}

Solution

  • The throw expression would need to be throw Error();, but yes, this is valid.

    Before the Error object can be thrown, it must be constructed. That is, the subexpression Error() must be evaluated before the throw operator can be evaluated in the full expression. If evaluation of the subexpression Error() itself throws an exception, the rest of the full expression (i.e., the throw) would not be evaluated.