I have an STL container and I need to perform an action on each element in the container. But if the action fails on any element, I want to reverse the action on any elements that have already been changed.
For example, if I had an STL vector with pointers to a number bankAccount classes and wanted to increase each one by $50. But if any of the bank accounts fail to increase by 50, I want to cancel the increase entirely and decrease by $50 any of the accounts that have already been increased.
std::vector<bankAccount*> bankAccounts;
std::vector<bankAccount*>::iterator iter;
for (iter = bankAccounts.begin(); iter != bankAccounts.end(); ++iter)
{
try
{
iter->increaseBalance(50);
}
catch (...)
{
// One of the bankAccounts failed to increase by 50, now I need to go
// back and decrease by 50 all of the bankAccounts that have already
// been increased.
}
}
Is there any elegant way to do this? Maybe with STL algorithms or using reverse iterators?
catch (...)block, you cannot know what exception was thrown and the only sensible ways to leave such a catch block are either to rethrow the exception or to terminate the application. - James McNellis