Reputation: 1187
I've run into a problem regarding exceptions.
The code is shown below,
try
{
auto it = set_difference(allInterfaces.begin(), allInterfaces.end(), eths.begin(),
eths.end(), newCards.begin());
}
catch(...)
{
cout << "exception thrown << endl;
}
I know set_difference() is throwing an exception but the programs exits and the catch block doesn't catch the exception. Is there a way to catch the exception? I thought the catch all should always work.
Thanks for any help.
Upvotes: 0
Views: 336
Reputation: 109089
set_difference
will write the elements that are unique to either of the input sets to the output range you pass in. It's your responsibility to ensure that that range is large enough to contain the result. Otherwise, you'll walk off beyond the bounds of the range, resulting in undefined behavior. No exception is thrown when this happens, the best indicator you can hope for is an assertion failure in unoptimized builds (and there's no guarantee for that either).
Assuming newCards
is a container that supports push_back
, the easiest way to prevent this is to use std::back_insert_iterator
, which will call push_back
every time an object is assigned to it.
auto it = set_difference(allInterfaces.begin(), allInterfaces.end(),
eths.begin(), eths.end(), std::back_inserter(newCards));
The other options available are std::front_insert_iterator
(calls push_front()
) and std::insert_iterator
(calls insert()
). Choose the one that suits your needs best.
Upvotes: 2
Reputation: 409136
With the help of your comment, it's very likely that you increase and iterate the iterator returned from newCards.begin()
, even beyond the bounds of the vector. This leads to undefined behavior (which in your case causes a crash) and not to a thrown C++ exception. Iterator access is not bounds-checked in C++ (very few things are).
To solve this you need to pass in the end of the newCards
vector as well, and make sure you don't step out of bounds.
Upvotes: 1