Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
}
like image 549
WilliamKF Avatar asked Nov 19 '25 06:11

WilliamKF


1 Answers

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.

like image 114
James McNellis Avatar answered Nov 20 '25 22:11

James McNellis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!