Will the following append() in the catch cause the rethrown exception to see the effect of append() being called?
try {
mayThrowMyErr();
} catch (myErr &err) {
err.append("Add to my message here");
throw; // Does the rethrow exception reflect the call to append()?
}
Similarly, if I rewrite it this way, will bit slicing occur if the actual exception is derived by myErr?
try {
mayThrowObjectDerivedFromMyErr();
} catch (myErr &err) {
err.append("Add to my message's base class here");
throw err; // Do I lose the derived class exception and only get myErr?
}
In both cases, since you catch by reference, you are effectively altering the state of the original exception object (which you can think of as residing in a magical memory location which will stay valid during the subsequent unwinding —
0x98e7058in the example below). However,throw;(which, unlikethrow err;, preserves the original exception object, with your modifications, in said “magical location” at0x98e7058) will reflect the call to append()errwill be created then thrown anew (at a different “magical location”0x98e70b0— because for all the compiler knowserrcould be an object on the stack about to be unwinded, likeewas at0xbfbce430, not in the “magical location” at0x98e7058), so you will lose derived-class-specific data during the copy-construction of a base class instance.Simple program to illustrate what’s happening:
Result:
Also see: