简体   繁体   中英

re throwing const exception reference

I have been asked in a multiple-choice question what is doing the following program doing:

catch(const std::exception& e){
  throw e;
}

I answered that it was rethrowing e (answer C). But the answer was apparently wrong.

So what is it doing ? Throwing a copy of e (answer D)?

The other possible answer were: A)Handles the exception B) Capture the current stack trace in e

Thanks

throw statement makes a copy of its argument. That means throw e; slices e to its base class (or whatever the static type of e is). To re-throw the original exception use throw; .

It throws a copy of e . Answer D is correct.

To simply re-throw do:

catch(const std::exception& e) {
    throw;
}

It's doing exactly what is says on the tin : you're re-throwing e . Conceptually a value copy of e is taken although compilers can optimise away any deep copy if there is no side effect in doing so.

To guarantee that no copy is made, just write throw; .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM